views:

84

answers:

5

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. 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.

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

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

len(set(d_1.keys()).difference(d_2.keys())) == 0
Alex
SilentGhost's reply will return false if the keys are the same but the values are different
Alex
Checking for len == 0 is probably the most unpythonic thing.
SilentGhost
+5  A: 

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

gnibbler
A: 

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)
The MYYN
+3  A: 

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.

xorsyst
you don't need `keys` there.
SilentGhost
Even easier than this, since set(dict) gives just the keys...
Andrew Jaffe
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
@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.
ΤΖΩΤΖΙΟΥ