randomThought randomThought - 1 month ago 9
Python Question

Is there a better way to compare dictionary values

I am currently using the following function to compare dictionary values. Is there a faster or better way to do it?

match = True
for keys in dict1:
if dict1[keys] != dict2[keys]:
match = False
print keys
print dict1[keys],
print '->' ,
print dict2[keys]


Edit: Both the dicts contain the same keys.

Answer

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.

Comments