Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing 2 dictionaries: same key, mismatching values

Tags:

python

I am currently trying to compare 2 data sets:

dict1 = {'a':1, 'b':2, 'c':3}
dict2 = {'a':1, 'b':2, 'c':4}

In this case I want the output to be something like:

set1 = set([('c', 4), ('c',3)])

since their keys match but values do not.

I've tried a variation of comprehensions using the intersection and difference operators but I cannot get the desired output.

Any help is appreciated.

like image 860
dyao Avatar asked Nov 29 '22 09:11

dyao


2 Answers

If you are using Python 2:

dict1.viewitems() ^ dict2.viewitems()

If you are using Python 3:

dict1.items() ^ dict2.items()

viewitems (Python 2) and items (Python 3) return a set-like object, which we can use the caret operator to calculate the symetric difference.

like image 140
Hai Vu Avatar answered Dec 06 '22 20:12

Hai Vu


set(dict1.items()).symmetric_difference(dict2.items())

Use iteritems in Python 2 for better efficiency.

like image 23
Alex Hall Avatar answered Dec 06 '22 20:12

Alex Hall