Timothy Tran
Timothy Tran

Reputation: 101

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. 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).

Upvotes: 2

Views: 263

Answers (2)

dparadis28
dparadis28

Reputation: 101

you can also take advantage of the intersection property built into sets

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

Upvotes: 3

Alex Hall
Alex Hall

Reputation: 36033

Use .items() to convert each dictionary into an iterable of (key, value) tuples, convert those iterables to sets, then collapse them all with intersection:

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.

Upvotes: 0

Related Questions