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.
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.
You can use set intersection on the dictionaries keys() . Then loop over those and check if the values corresponding to those keys are identical.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With