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:]))]
執行結果:python
['g']
#1.使用字典的keys()方法,獲得一個字典keys的集合 #2.使用map函數,獲得每一個字典keys的集合 #3.使用reduce函數,取全部字典的keys集合的交集 from functools import reduce reduce(lambda a, b: a & b, map(dict.keys, dl))
執行結果:dom
{'g'}