PythonMastery

Find common keys in two dictionaries in Python

Find the keys two dictionaries share with keys() & keys(), and also the keys only one of them has, and the keys whose values differ.

The keys of a dictionary behave like a set, so you can use set operators on them directly. & gives the keys that are in both dictionaries.

The program

python
last_week = {"apple": 30, "banana": 12, "cherry": 5}
this_week = {"banana": 15, "cherry": 5, "mango": 18}

common = last_week.keys() & this_week.keys()
print("In both weeks:", sorted(common))

for fruit in sorted(common):
    print(f"{fruit}: {last_week[fruit]} -> {this_week[fruit]}")
output
In both weeks: ['banana', 'cherry']
banana: 12 -> 15
cherry: 5 -> 5

How it works

What changed between the two

python
last_week = {"apple": 30, "banana": 12, "cherry": 5}
this_week = {"banana": 15, "cherry": 5, "mango": 18}

print("Removed:", sorted(last_week.keys() - this_week.keys()))
print("Added:  ", sorted(this_week.keys() - last_week.keys()))

changed = [k for k in sorted(last_week.keys() & this_week.keys())
           if last_week[k] != this_week[k]]
print("Changed:", changed)
output
Removed: ['apple']
Added:   ['mango']
Changed: ['banana']

This is the start of a simple "diff" of two dictionaries: keys that were removed, keys that were added, and shared keys whose value is different.

Learn the idea: Dictionaries, Sets: Unordered, Unique, Lightning Fast