举例
在三个字典中找出都存在的键
一般方法
从一个字典中依次遍历键,然后判断其余两个字典是否存在这个键。代码如下:
from random import randit, sample
s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
sample是一个随机采样函数
这样做逻辑上比较简单,但是效率不高
使用集合的方式
首先使用viewkeys()的方法,得到一个字典,然后分别用map和reduce函数得到所有字典键的集合和所有集合的交集。代码如下:
字典个数比较少的情况下
from random import randit, sample
s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s1.viewkeys() & s2.viewkeys() & s3.viewkeys()
当字典个数比较多的情况下
假设要求n个字典的公共键的集合,代码如下:
from random import randit, sample
s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
reduce(lambda a, b: a & b, map(dict.viewkeys, [s1, s2, s3,...,sn]))