Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to check if two dictionaries have the identical set of keys?

For example, let's say I have to dictionaries:

d_1 = {'peter': 1, 'adam': 2, 'david': 3} 

and

d_2 = {'peter': 14, 'adam': 44, 'david': 33, 'alan': 21} 

What's the cleverest way to check whether the two dictionaries contain the same set of keys? In the example above, it should return False because d_2 contains the 'alan' key, which d_1 doesn't.

I am not interested in checking that the associated values match. Just want to make sure if the keys are same.

like image 470
c00kiemonster Avatar asked Jul 09 '10 07:07

c00kiemonster


People also ask

How do I tell if two dictionaries are identical in Python?

Use == operator to check if the dictionaries are equal You can create the dictionaries with any of the methods defined in Python and then compare them using the == operator. It will return True the dictionaries are equals and False if not.

How do you compare two dictionaries with the same key in Python?

You can use set intersection on the dictionaries keys() . Then loop over those and check if the values corresponding to those keys are identical.


2 Answers

You can get the keys for a dictionary with dict.keys().

You can turn this into a set with set(dict.keys())

You can compare sets with ==

To sum up:

set(d_1.keys()) == set(d_2.keys()) 

will give you what you want.

like image 40
xorsyst Avatar answered Sep 25 '22 05:09

xorsyst


In Python2,

set(d_1) == set(d_2) 

In Python3, you can do this which may be a tiny bit more efficient than creating sets

d1.keys() == d2.keys() 

although the Python2 way would work too

like image 79
John La Rooy Avatar answered Sep 22 '22 05:09

John La Rooy