Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to find "key" difference between 2 dictionaries?

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?

like image 551
Sam Goldberg Avatar asked Apr 22 '12 23:04

Sam Goldberg


People also ask

How do you compare keys in two dictionaries?

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 find the difference between two dictionaries in Python?

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.

Can you compare two dictionaries in Python?

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.

How do you compare two dictionaries with the same key in Python?

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 .


3 Answers

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}
like image 66
DSM Avatar answered Sep 19 '22 16:09

DSM


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])
like image 21
Zbyszek Mandziejewicz Avatar answered Sep 21 '22 16:09

Zbyszek Mandziejewicz


Maybe

[x for x in dict1.keys() if x not in dict2.keys()]
like image 41
user1245262 Avatar answered Sep 21 '22 16:09

user1245262