For example, let\'s say I have to dictionaries:
d_1 = {\'peter\': 1, \'adam\': 2, \'david\': 3}
and
d_2 = {\'peter\': 14, \
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)
>>> not set(d_1).symmetric_difference(d_2)
False
>>> not set(d_1).symmetric_difference(dict.fromkeys(d_1))
True
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.
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)
A quick option (not sure if its the most optimal)
len(set(d_1.keys()).difference(d_2.keys())) == 0
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