I needed to compare 2 dictionaries to find the set of keys in one dictionary which was not in the other.
I know that Python set objects support:
set3=set1-set2
but I can't do:
dict3=dict1-dict2
or:
missingKeys=dict1.keys()-dict2.keys()
(I was a little surprised by the last point, because in Java the keys are a Set object.) One solution is:
missingKeys=set(dict1.keys())-set(dict2.keys())
is there a better or more concise way to do this?
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.
With set. Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second.
The easiest way (and one of the more robust at that) to do a deep comparison of two dictionaries is to serialize them in JSON format, sorting the keys, and compare the string results: import json if json. dumps(x, sort_keys=True) == json.
To compare two dictionaries and checking how many (key, value) pairs are equal with Python, we can use dict comprehension. to get the values in dict x if they're key k is in dict y and x[k] is equal to y[k] . And then we check the length of the shared_items dict to see which items are the same in both dicts x and y .
Python 2.7:
>>> d = {1:2, 2:3, 3:4}
>>> d2 = {2:20, 3:30}
>>> set(d)-set(d2)
set([1])
Python 3.2:
>>> d = {1:2, 2:3, 3:4}
>>> d2 = {2:20, 3:30}
>>> d.keys()-d2.keys()
{1}
For portable way of doing it I would suggest using dict.viewkeys in Python 2.7 - it is backport of Python 3.x dict.keys and is automatically converted by 2to3.
Example:
>>> left = {1: 2, 2: 3, 3: 4}
>>> right = {2: 20, 3:30}
>>> left.viewkeys() - right.viewkeys()
set([1])
Maybe
[x for x in dict1.keys() if x not in dict2.keys()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With