快速查找字典中的公共键

举例


在三个字典中找出都存在的键

一般方法


从一个字典中依次遍历键,然后判断其余两个字典是否存在这个键。代码如下:

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]))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值