Question

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?

Was it helpful?

Solution

Maybe

[x for x in dict1.keys() if x not in dict2.keys()]

OTHER TIPS

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

This should work in Python 2.7 and 3.x:

>>> keys = getattr(dict, 'viewkeys', dict.keys)
>>> left = {1: 2, 2: 3, 3: 4}
>>> right = {2: 20, 3:30} 
>>> list(keys(left) - keys(right))
[1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top