Comparing Dictionaries in Python

It’s possible to use simple logical operator on dictionaries to compare them like finding keys that are in both dictionaries

>>> dict1 = {'x': 1, 'y': 2, 'z': 3}
>>> dict2 = {'t': 10, 'x': 1, 'y': 30}
>>> dict1.keys() & dict2.keys()
{'x', 'y'}

or keys that are in the first dictionary but not in the second one

>>> dict1.keys() - dict2.keys()

find keys/values that are in common

>>> dict1.items() & dict2.items()
{'x': 1}

Even better, those logical operator can be used in dictionary comprehension to create a new dictionary with some keys removed

>>> dict3 = {key:dict1[key] for key in dict1.keys() - {'x'}
>>> dict3
{'y': 2, 'z': 3}