from random import randint, sample #sample随机取样
d1 = {k: randint(1, 4) for k in sample('abcdefgh', randint(3, 6))} #产生数据
d2 = {k: randint(1, 4) for k in sample('abcdefgh', randint(3, 6))}
d3 = {k: randint(1, 4) for k in sample('abcdefgh', randint(3, 6))}
#方法1:for循环 + 列表解析
[k for k in d1 if k in d2 and k in d3]
#方法2:map
dl = [d1, d2, d3]
[k for k in dl[0] if all(map(lambda d: k in d, dl[1:]))]
执行结果:
['g']
利用集合(set)的交集操作
#1.使用字典的keys()方法,得到一个字典keys的集合
#2.使用map函数,得到每个字典keys的集合
#3.使用reduce函数,取所有字典的keys集合的交集
from functools import reduce
reduce(lambda a, b: a & b, map(dict.keys, dl))
执行结果:
{'g'}