Add values of matching keys
EasyDictionary Programs · 32 of 94
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}
True Approach
- Start with a copy of the first dict and add the second’s values with
get.
Solution
Python
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}
True
Line by line
Line 5Keys only in d2 start from 0.
Line 8Counter addition does the same for positive values.
Learn the concept
New to this topic? Read the lesson, then come back.
More dictionary programs
← All 94 Dictionary Programs