Skip to content Skip to sidebar Skip to footer

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

Solution 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

Solution 2:

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.

Solution 3:

  • 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) andall(k in d_2 for k in d_1)
    

Solution 4:

>>> notset(d_1).symmetric_difference(d_2)
False>>> notset(d_1).symmetric_difference(dict.fromkeys(d_1))
True

Solution 5:

One way is to check for symmetric difference (new set with elements in either s or t but not both):

set(d_1.keys()).symmetric_difference(set(d_2.keys()))

But a shorter way it to just compare the sets:

set(d_1) == set(d_2)

Post a Comment for "Pythonic Way To Check If Two Dictionaries Have The Identical Set Of Keys?"