Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to compare dictionary values

I am currently using the following function to compare dictionary values and display all the values that don't match. 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.

like image 765
randomThought Avatar asked Dec 15 '09 23:12

randomThought


People also ask

How do you compare values in a dictionary?

Python List cmp() Method. The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

Can you compare dictionaries in Python?

You can use the == operator, and it will work. However, when you have specific needs, things become harder. The reason is, Python has no built-in feature allowing us to: compare two dictionaries and check how many pairs are equal.


1 Answers

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 "==".

like image 57
ThomasH Avatar answered Sep 19 '22 15:09

ThomasH