python – Is there a better way to compare dictionary values

python – Is there a better way to compare dictionary values

If the true intent of the question is the comparison between dicts (rather than printing differences), the answer is

dict1 == dict2

This has been mentioned before, but I felt it was slightly drowning in other bits of information. It might appear superficial, but the value comparison of dicts has actually powerful semantics. It covers

  • number of keys (if they dont match, the dicts are not equal)
  • names of keys (if they dont match, theyre not equal)
  • value of each key (they have to be ==, too)

The last point again appears trivial, but is acutally interesting as it means that all of this applies recursively to nested dicts as well. E.g.

 m1 = {f:True}
 m2 = {f:True}
 m3 = {a:1, 2:2, 3:m1}
 m4 = {a:1, 2:2, 3:m2}
 m3 == m4  # True

Similar semantics exist for the comparison of lists. All of this makes it a no-brainer to e.g. compare deep Json structures, alone with a simple ==.

If the dicts have identical sets of keys and you need all those prints for any value difference, there isnt much you can do; maybe something like:

diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
  print k, :, dict1[k], ->, dict2[k]

pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.

python – Is there a better way to compare dictionary values

You can use sets for this too

>>> a = {x: 1, y: 2}
>>> b = {y: 2, x: 1}
>>> set(a.iteritems())-set(b.iteritems())
set([])
>>> a[y]=3
>>> set(a.iteritems())-set(b.iteritems())
set([(y, 3)])
>>> set(b.iteritems())-set(a.iteritems())
set([(y, 2)])
>>> set(b.iteritems())^set(a.iteritems())
set([(y, 3), (y, 2)])

Leave a Reply

Your email address will not be published. Required fields are marked *