Python教程

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

本文主要是介绍【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学习交流群: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;
这篇关于【Python基础教程】快速找到多个字典中的公共键(key)的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!