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 "==".
If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't 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.