简体   繁体   English

在字典列表中找到相同的键值对的最佳方法

[英]Best Way to find Identical Key-Value pairs in List of Dictionaries Python

If I have a list of dictionaries such as 如果我有字典清单,例如

[{'D': 'wet', 'W': 'sun'}, {'D': 'wet', 'W': 'rain'}, {'D': 'wet', 'W': 'sun'}]

What would be the best way to detect if there is a Key-Value pair that is identical between all dictionaries in the list. 检测列表中所有字典之间是否存在相同的键值对的最佳方法是什么。 So in this case, "D" : "Wet" would be identical because it is the same across all the Key and Values of the list of dictionaries. 因此,在这种情况下,“ D”:“湿”将是相同的,因为在字典列表的所有键和值中它都是相同的。 However, the "W" will not be because it has more a >1 domain (sun and rain are both in the domain of the W key). 但是,“ W”将不是因为它具有更多的> 1域(太阳和雨都在W键的域中)。

您还可以利用内置在集合中的交集属性

dict(set.intersection(*(set(d.items()) for d in dicts)))

Use .items() to convert each dictionary into an iterable of (key, value) tuples, convert those iterables to sets, then collapse them all with intersection: 使用.items()将每个字典转换为(key, value)元组的可迭代(key, value) ,将这些可迭代项转换为集合,然后使用交集将其全部折叠:

reduce(lambda a, b: a & b,
       (set(d.items()) for d in
        [{'D': 'wet', 'W': 'sun'}, {'D': 'wet', 'W': 'rain'}, {'D': 'wet', 'W': 'sun'}]))

In Python 3 you will need from functools import reduce . 在Python 3中,您需要from functools import reduce

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM