Finding Commonalities in Two Dictionaries
Problem
- You have two dictionaries and want to find out what they might have in common (same keys, same values, etc.).
Solution
- Perform common set operations using the
keys()
or items()
methods
a = {
'x' : 1,
'y' : 2,
'z' : 3 }
b = {
'w' : 10,
'x' : 11,
'y' : 2 }
a.keys() & b.keys()
{'x', 'y'}
a.keys() - b.keys()
{'z'}
a.items() & b.items()
{('y', 2)}
- These kinds of operations can also be used to alter or filter dictionary contents. For example, suppose you want to make a new dictionary with selected keys removed.
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
print(c)
{'y': 2, 'x': 1}