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.
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.
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.
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.
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'}
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.
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