Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two dictionaries in Python?

I have two dictionaries, and I need to find the difference between the two, which should give me both a key and a value.

I have searched and found some addons/packages like datadiff and dictdiff-master, but when I try to import them in Python 2.7, it says that no such modules are defined.

I used a set here:

first_dict = {} second_dict = {}   value = set(second_dict) - set(first_dict) print value 

My output is:

>>> set(['SCD-3547', 'SCD-3456']) 

I am getting only keys, and I need to also get the values.

like image 550
Jayashree Shetty Avatar asked Sep 28 '15 04:09

Jayashree Shetty


People also ask

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.

How do you subtract a value between two dictionaries in Python?

Method #2 : Using Counter() + “-” operator In this, the Counter function converts the dictionary in the form in which the minus operator can perform the task of subtraction.

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.


2 Answers

I think it's better to use the symmetric difference operation of sets to do that Here is the link to the doc.

>>> dict1 = {1:'donkey', 2:'chicken', 3:'dog'} >>> dict2 = {1:'donkey', 2:'chimpansee', 4:'chicken'} >>> set1 = set(dict1.items()) >>> set2 = set(dict2.items()) >>> set1 ^ set2 {(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')} 

It is symmetric because:

>>> set2 ^ set1 {(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')} 

This is not the case when using the difference operator.

>>> set1 - set2 {(2, 'chicken'), (3, 'dog')} >>> set2 - set1 {(2, 'chimpansee'), (4, 'chicken')} 

However it may not be a good idea to convert the resulting set to a dictionary because you may lose information:

>>> dict(set1 ^ set2) {2: 'chicken', 3: 'dog', 4: 'chicken'} 
like image 63
Roedy Avatar answered Sep 19 '22 05:09

Roedy


Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) } 

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

like image 34
Óscar López Avatar answered Sep 21 '22 05:09

Óscar López