查找一些词典的通用键 [英] Find common keys of a number of dictionaries

查看:74
本文介绍了查找一些词典的通用键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约20000个字典。我想找到所有字典中都通用的所有键(该键必须在所有20000个字典中都存在)。如何实现这一目标。目前,我正在写类似的东西,但是它没有给我期望的结果:

I have around 20000 dictionaries.I want find all the keys which are common in all the dictionary(that key need to be present in all 20000) dictionary.How can I achieve this.Currently I am writing something like that,But its not giving me the desired result:

if parsedData.keys() not in uniquelist: 
            uniquelist.append(parsedData.keys())
        else:
            commonlist.append(parsedData.keys())

这里解析的数据是我的字典。

here parsed data is my dictionary. Please help me with this.

推荐答案

您可以在第一个字典中创建一组键,然后以循环形式创建

You could create the set of the keys in the first dictionary and then in a loop form the intersection with the remaining keys:

>>> d1 = {'a':1, 'b':2, 'c':3}
>>> d2 = {'b':4, 'c':7,'d':5}
>>> d3 = {'b':5, 'c':8,'e':6}
>>> dicts = [d1,d2,d3]
>>> common_keys = set(d1.keys())
>>> for d in dicts[1:]:
    common_keys.intersection_update(set(d.keys()))

>>> common_keys
{'b', 'c'}

这篇关于查找一些词典的通用键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆