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
last_week.keys()is a view of the keys. Key views support the set operators&,|,-and^, and the result is a normal set.- A set of strings has no fixed order, so
sorted()makes the output the same every time. - Once you have the common keys, you can read both values for each key to compare them.
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.