如何快速找到多个字典的公共键(key)?

需求:
西班牙甲级联赛,每轮球员进球统计:
第一轮:{'苏亚雷斯':1,'梅西':2,'本泽马':1...}
第二轮:{'苏亚雷斯':1,'C罗':1'格里兹曼':2...}
第三轮:{'苏亚雷斯':1,'托雷斯':2,'贝尔':1...}
统计出前N轮,每场比赛都有进球的球员

思路:
方法一:利用for对每个字典进行迭代,进行in来进行判断
方法二:利用集合(set)的交集操作
1、使用字典的keys方法得到一个字典的keys的集合
2、使用map函数,得到每个字典的集合
3、使用reduce函数,取所有字典keys集合的交集

代码:

# 方法一:
>>> from random import randint,sample
>>> sample('abcdefg',3)
['a', 'g', 'e']
>>> sample('abcdefgh',randint(3,6))
['d', 'g', 'b', 'f', 'e']
>>> 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))}

>>> d1
{'a': 1, 'e': 4, 'b': 1, 'd': 3, 'g': 3, 'f': 4}

>>> d2
{'c': 4, 'f': 4, 'g': 3, 'e': 4, 'b': 3}

>>> d3
{'e': 2, 'd': 1, 'b': 4, 'a': 1}

>>> for k in d1:
...     if k in d2 and k in d3:
...         print(k)
... 
e
b

>>> [ k for k in d1 if k in d2 and k in d3]
['e', 'b']

>>> dl = [d1,d2,d3] # dl的长度不定长

>>> [ k for k in dl[0] if all(map(lambda d: k in d,dl[1:]))] # map返回的是true或者false的集合,更具有普遍性
['e', 'b']

# 方法二:
>>> s1 = d1.keys()

>>> s1
dict_keys(['a', 'e', 'b', 'd', 'g', 'f'])

>>> s2 = d2.keys()

>>> s2
dict_keys(['c', 'f', 'g', 'e', 'b'])

>>> s1 & s2
{'b', 'e', 'f', 'g'}

>>> reduce
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-37-62f6239f03f9> in <module>
----> 1 reduce

NameError: name 'reduce' is not defined

>>> from functools import reduce

>>> reduce(lambda a,b:a * b,range(1,11))
3628800

>>> dl
[{'a': 1, 'e': 4, 'b': 1, 'd': 3, 'g': 3, 'f': 4},
 {'c': 4, 'f': 4, 'g': 3, 'e': 4, 'b': 3},
 {'e': 2, 'd': 1, 'b': 4, 'a': 1}]

>>> d1.keys
<function dict.keys>

>>> d1.keys()
dict_keys(['a', 'e', 'b', 'd', 'g', 'f'])

>>> dict.keys(d1)
dict_keys(['a', 'e', 'b', 'd', 'g', 'f'])

>>> map(dict.keys,dl)
<map at 0x7f3ae8277c50>

>>> list(map(dict.keys,dl))
[dict_keys(['a', 'e', 'b', 'd', 'g', 'f']),
 dict_keys(['c', 'f', 'g', 'e', 'b']),
 dict_keys(['e', 'd', 'b', 'a'])]

>>> reduce(lambda a,b :a & b ,map(dict.keys,dl))
{'b', 'e'}
原文地址:https://www.cnblogs.com/Richardo-M-Q/p/13902084.html