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.
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.
set(dict1.items()).symmetric_difference(dict2.items())
Use iteritems
in Python 2 for better efficiency.
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