Sign up ×

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

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


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. Please note that I am not interested in checking that the associated values for each and every key are the same, just that the set of keys are the same.

share|improve this question

5 Answers 5

up vote 8 down vote accepted

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.

share|improve this answer
you don't need keys there. – SilentGhost Jul 9 '10 at 8:09
Even easier than this, since set(dict) gives just the keys... – Andrew Jaffe Jul 9 '10 at 8:10
True, you don't need the keys, but if you don't use sets very often I'd say that the behaviour of set(dictionary) is non-obvious. Does anyone know if using keys introduces a performance hit? – xorsyst Jul 9 '10 at 13:06
@xorsyst: in Python 2 iter(a_dict) returns an iterator, a_dict.keys() returns a list; therefore, set(d_1.keys()) incurs the creation and destruction of a temporary list of the dictionary keys. In Python 3, they're equivalent. – tzot Jul 11 '10 at 9:24
@Joschua: If you are familiar with list(some_dict), then I agree set(some_dict) should be pretty obvious. But to me, it's not at all obvious that these would work the way they do. My first expectation is that list(some_dict) would be a list of (key, value) tuples. I agree that returning just the keys is a useful behaviour, but I wouldn't say it was "obvious". – xorsyst Mar 7 '11 at 9:25

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

share|improve this answer
+1 for the Python 3 way – Joschua Mar 5 '11 at 19:33
>>> not set(d_1).symmetric_difference(d_2)
>>> not set(d_1).symmetric_difference(dict.fromkeys(d_1))
share|improve this answer

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


But a shorter way it to just compare the sets:

set(d_1) == set(d_2)
share|improve this answer

A quick option (not sure if its the most optimal)

len(set(d_1.keys()).difference(d_2.keys())) == 0
share|improve this answer
SilentGhost's reply will return false if the keys are the same but the values are different – Alex Jul 9 '10 at 8:07
Checking for len == 0 is probably the most unpythonic thing. – SilentGhost Jul 9 '10 at 8:10

Your Answer


