Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: find only common key-value pairs of several dicts: dict intersection

Tags:

python

I have 0 or more dicts in a list:

>>> dicts = [dict(a=3, b=89, d=2), dict(a=3, b=89, c=99), dict(a=3, b=42, c=33)]

I want to create a new dict that contains only keys that are in all the above dicts, and only if the values are all the same:

>>> dict_intersection(*dicts)
{"a": 3}

I feel that there should be an elegant way of writing dict_intersection, but I'm only coming up with inelegant and/or inefficient solutions myself. Suggestions?

like image 730
Lauritz V. Thaulow Avatar asked Mar 28 '12 11:03

Lauritz V. Thaulow


People also ask

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

How do I compare two dictionary keys and values in Python?

Python List cmp() Method. The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

How do you iterate through key-value pairs?

To iterate over key-value pairs, use the following: for k,v in dict. iteritems() in Python 2. for k,v in dict.


1 Answers

>>> dict(set.intersection(*(set(d.iteritems()) for d in dicts)))
{'a': 3}

Note: This solution requires the dictionary values to be hashable, in addition to the keys.

like image 87
interjay Avatar answered Oct 22 '22 00:10

interjay