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 don’t match, the dicts are not equal)
  • names of keys (if they don’t match, they’re 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 “==”.

Leave a Comment