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:循環(huán)判斷
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
方案2:集合交集
s1.keys() & s2.keys() & s3.keys()
如何解決字典個數(shù)不定的情況呢扮匠?
可以使用map,reduce函數(shù)
s = map(dict.keys(), [s1,s2,s3])
reduce(lambda a,b: a&b,s)