easy +10 pts

Merge dicts summing values

Combine multiple dictionaries, summing values for duplicate keys.

Write a function `merge_dicts_sum(d1, d2)` that takes two dictionaries `d1` and `d2` where all values are integers. It returns a new dictionary containing all keys from both dictionaries. If a key appears in both dictionaries, its value in the result should be the sum of its values from `d1` and `d2`. The input dictionaries must not be modified. The order of keys in the result does not matter.

Constraints

The dictionaries may be empty. All values are integers. Keys can be any hashable type. The function should not mutate the input dictionaries.

Example

>>> merge_dicts_sum({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
{'a': 1, 'b': 5, 'c': 4}
>>> merge_dicts_sum({}, {'x': 10})
{'x': 10}
>>> merge_dicts_sum({'k': -1}, {'k': 1})
{'k': 0}
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Start with a copy of one dictionary to avoid modifying it.
Iterate over the other dictionary’s items and add values.
If a key already exists, add the value; otherwise, set it.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.