How do we compare two dictionaries in Python?



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)}
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements