A short way to find the “key” difference between two dictionaries?

I needed to compare 2 dictionaries to find a set of keys in one dictionary that was not in another.

I know Python object support:

set3=set1-set2 

but I can not:

 dict3=dict1-dict2 

or

 missingKeys=dict1.keys()-dict2.keys() 

(I was a bit surprised at the last point, because in Java, keys are Set objects.) One solution:

 missingKeys=set(dict1.keys())-set(dict2.keys()) 

Is there a better or more concise way to do this?

+6
source share
4 answers

Can

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

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} 
+15
source

For a portable way to do this, I would suggest using dict.viewkeys in Python 2.7 - this is a backport from Python 3.x dict.keys and will automatically convert to 2to3.

Example:

 >>> left = {1: 2, 2: 3, 3: 4} >>> right = {2: 20, 3:30} >>> left.viewkeys() - right.viewkeys() set([1]) 
+4
source

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] 
+1
source

Source: https://habr.com/ru/post/913876/


All Articles