How do we compare two dictionaries in Python?

PythonProgramming

dicts in python are also classes. These have the __eq__method overridden, so you can use the == operator to check if 2 dictionaries are equal or not.

example

a = {'foo': 10, 'bar': 150}
b = {'foo': 10, 'bar': 150}
print(a == b)

Output

This will give the output −

True

If you want a list of shared items in the 2 dictionaries, you can use sets and the & operator on them to get that.

example

a = {'foo': 10, 'bar': 150}
b = {'foo': 10, 'baz': 50}

shared = set(a.items()) & set(b.items())
print(shared)

Output

This will give the output −

{('foo', 10)}
Published on 18-Apr-2018 13:57:34