dyao dyao - 1 year ago 42
Python Question

Comparing 2 dictionaries: same key, mismatching values

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.

Answer Source

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.