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

>>> not set(d_1).symmetric_difference(d_2)
False
>>> not set(d_1).symmetric_difference(dict.fromkeys(d_1))
True

  • In Python 3, dict.keys() returns a "view object" that can be used like a set. This is much more efficient than constructing a separate set.

    d_1.keys() == d_2.keys()
    
  • In Python 2.7, dict.viewkeys() does the same thing.

    d_1.viewkeys() == d_2.viewkeys()
    
  • In Python 2.6 and below, you have to construct a set of the keys of each dict.

    set(d_1) == set(d_2)
    

    Or you can iterate over the keys yourself for greater memory efficiency.

    len(d_1) == len(d_2) and all(k in d_2 for k in d_1)
    

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


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.