Python快速查找多个字典中的公共键(key)

Jackey Python 700 次浏览 , 没有评论
from functools import reduce
from random import randint, sample

# 获取多个字典中相同的key
data1 = sample('abcdefg', 3)
print(data1)
data2 = sample('abcdefg', randint(3, 6))
print(data2)
s1 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
print(s1)
s2 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
print(s2)
s3 = {x: randint(1, 4) for x in sample('abcdefg', randint(3, 6))}
print(s3)

# 第一种方法
res = []
for k in s1:
    if k in s2 and k in s3:
        res.append(k)
print(res)

# 第二种方法
print(s1.keys())
# 取交集
print(s1.keys() & s2.keys() & s3.keys())
resMap = map(dict.keys, [s1, s2, s3])
print('-----')
print(list(resMap))

# 第三种方法
res = reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3]))
print(res)

 

发表评论

您的电子邮箱地址不会被公开。

Go