Python Practice › Dictionary Programs › Program 32
Add values of matching keys
Write a Python program to combine two dictionaries, adding the values of keys that appear in both.
Input
{"x": 10, "y": 20, "c": 50, "f": 44}, {"x": 60, "c": 25, "y": 56}Output
{'x': 70, 'y': 76, 'c': 75, 'f': 44}
TrueApproach
- Start with a copy of the first dict and add the second’s values with
get.
Solution
d1 = {"x": 10, "y": 20, "c": 50, "f": 44}d2 = {"x": 60, "c": 25, "y": 56}total = d1.copy()for k, v in d2.items(): total[k] = total.get(k, 0) + vprint(total) from collections import Counterprint(dict(Counter(d1) + Counter(d2)) == total)Output
{'x': 70, 'y': 76, 'c': 75, 'f': 44}
TrueLine by line
Line 5
Keys only in d2 start from 0.
Line 8
Counter addition does the same for positive values.
Learn the concept
New to this topic? Read the lesson, then come back.