Pythonic Way to Check If Two Dictionaries Have the Identical Set of Keys

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

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.

how to compare two dictionaries to check if a key is present in both of them

in on a dict will return if a key is present in a dictionary:

>>> a = {'b': 1, 'c': '2'}
>>> 'b' in a
True
>>> 'd' in a
False

So your code could be written as:

dict1 = {'1234': 'john','5678': 'james'};
dict2 = {'1234': 'technician'};

for key in dict1.keys():
print key
if key in dict2:
print dict1[key] + dict2[key]
else:
print dict1[key]

If you just want to check that the two are equal, you can do:

set(dict1) == set(dict2)

Python: How to know if two dictionary have the same keys

python 2.7

dict views:
Supports direct set operations, etc.

>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> dic1.viewkeys() == dic2.viewkeys()
True
>>> dic1.viewkeys() - dic2.viewkeys()
set([])
>>> dic1.viewkeys() | dic2.viewkeys()
set(['a', 'c', 'b'])

similarly in 3.x: (thx @lennart)

>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> dic1.keys() == dic2.keys()
True
>>> dic1.keys() - dic2
set()
>>> dic1.keys() | dic2
{'a', 'c', 'b'}

python 2.4+

set operation: direct iteration over dict keys into a set

>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> set(dic1) == set(dic2)
True

Python3 Determine if two dictionaries are equal

== works

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
True

I hope the above example helps you.

How to check if the keys of two dictionaries are the same

You can use dict.viewkeys it returns a set like view object:

>>> {'a':4, 'b':2}.viewkeys() == {'a':0, 'b':1}.viewkeys()
True

You can't rely on dict.keys in py2.x because it returns a list and the order of keys can be arbitrary.

>>> ['a', 'b', 'c'] == ['a', 'c', 'b']    #same keys, but not equal
False
>>> set(['a', 'b', 'c']) == set(['a', 'c', 'b']) #sets compare fine
True

On py3.x use dict.keys().

Comparing 2 dictionaries: same key, mismatching values

If you are using Python 2:

dict1.viewitems() ^ dict2.viewitems()

If you are using Python 3:

dict1.items() ^ dict2.items()

viewitems (Python 2) and items (Python 3) return a set-like object, which we can use the caret operator to calculate the symetric difference.



Related Topics



Leave a reply



Submit