如何快速找到多个字典中的公共键(key)
#随机选取3个
from random import randint, sample
sample('abcdefg',3)
#['a','f','a']
#随机选取任意个
s1 = sample('abcdefg',radint(3,6))
#['d', 'a', 'f', 'e']
#随机生成字典dict
s1 = {k:randint(2,6) for k in (sample('abcdefg',randint(3,6)))}
#{'a': 3, 'b': 4, 'c': 3, 'd': 2, 'e': 4, 'f': 3}
#字典解析
s2 = {k:randint(2,6) for k in (sample('abcdefg',randint(3,6)))}
s3 = {k:randint(2,6) for k in (sample('abcdefg',randint(3,6)))}
#方法一:
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
#方法二:
k1 = s1.keys()
k2 = s2.keys()
k3 = s3.keys()
k1 and k2 and k3
#方法三:
#每一个的keys集合
map(dict.keys(),[s1,s2,s3])
#交集
reduce(lambda a,b:a and b, map(dict.keys(),[s1,s2,s3]))
如何让字典保持有序
Python
中字典默认是不具有有序这样的性质的
使用collections.OrderdDict
,以OrderedDict
代替内置字典Dict
,依次将选手成绩存入OrderedDict
。
from collections import OrderedDict
d = OrderedDict()
d['Jim']=(1,35)
d['Lop']=(2,37)
d['kiu']=(3,40)
for k in d:print(k)
#按顺序读入