python找到多个字典中的公共键
生成字典
from random import randint,sample
s = 'abcdefg'
s1 = {x:randint(1,4) for x in sample(s,randint(3,6))}
s2 = {x:randint(1,4) for x in sample(s,randint(3,6))}
s3 = {x:randint(1,4) for x in sample(s,randint(3,6))}
方案1:循环判断
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
方案2:集合交集
s1.keys() & s2.keys() & s3.keys()
如何解决字典个数不定的情况呢?
可以使用map,reduce函数
s = map(dict.keys(), [s1,s2,s3])
reduce(lambda a,b: a&b,s)