【集合】查找多个字典中的公共键
from random import sample, randint from functools import reduce ''' 查找多个字典中的公共键 ''' # 法1: 通过获取键集合求交集 d1 = {x: randint(1, 4) for x in sample('abcdefg', randint(4, 6))} d2 = {x: randint(1, 4) for x in sample('abcdefg', randint(4, 6))} d3 = {x: randint(1, 4) for x in sample('abcdefg', randint(4, 6))} print(d1) print(d2) print(d3) print(d1.keys() & d2.keys() & d3.keys()) print('-' * 50) # 法2:使用map、reduce reduce会把运行结果当成下一次运算的参数 def get_keys(d): return d.keys() if __name__ == '__main__': l = list(map(get_keys, [d1, d2, d3])) print(l) print(reduce(lambda x, y: x & y, l))
运行结果:
{'f': 3, 'c': 3, 'a': 3, 'e': 4, 'd': 4, 'g': 1}
{'e': 4, 'c': 4, 'g': 4, 'd': 3}
{'f': 3, 'd': 3, 'c': 3, 'g': 4, 'b': 2}
{'g', 'd', 'c'}
--------------------------------------------------
[dict_keys(['f', 'c', 'a', 'e', 'd', 'g']), dict_keys(['e', 'c', 'g', 'd']), dict_keys(['f', 'd', 'c', 'g', 'b'])]
{'g', 'd', 'c'}