【Python基础教程】快速找到多个字典中的公共键(key)的方法

方法一:for in循环

from random import randint, sample

a1 = {k: randint(1, 4) for k in 'abcdefg'}
a2 = {k: randint(1, 4) for k in 'abc123456789'}
a3 = {k: randint(1, 4) for k in 'abcinubububu'}
a4 = {k: randint(1, 4) for k in 'abc89898989'}
r = []

for x in a1:
    if x in a2 and x in a3 and x in a4:
        r.append(x)
print(r)
randint(1, 4)  # 从1~4间随机取一个数

方法二:利用集合的交集操作

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from random import randint, sample

a1 = {k: randint(1, 4) for k in 'abcdefg'}
a2 = {k: randint(1, 4) for k in 'abcdefg'}
a3 = {k: randint(1, 4) for k in 'abcdefg'}
a4 = {k: randint(1, 4) for k in 'abcdefg'}

a = a1.keys() & a2.keys() & a3.keys() & a4.keys()
print(a)

a1.keys():得到a1字典的key,一set格式;
a1.keys() & a2.keys() & a3.keys() & a4.keys():取4个集合的公共元素;
a为一个集合(set)

方法三:使用map即reduce(用于求n个字典的公共key)

from random import randint, sample
from functools import reduce

a1 = {k: randint(1, 4) for k in 'abcdefg'}
a2 = {k: randint(1, 4) for k in 'abcdefg'}
a3 = {k: randint(1, 4) for k in 'abcdefg'}
a4 = {k: randint(1, 4) for k in 'abcdefg'}

b1 = map(dict.keys, [a1, a2, a3, a4])
b2 = reduce(lambda a ,b: a & b, b1)

print(b2)

b1 = map(dict.keys, [a1, a2, a3, a4])  #以集合形式取每个字典的keys;
posted @ 2022-10-07 20:26  I'm_江河湖海  阅读(71)  评论(0编辑  收藏  举报