Skip to content

5. Merge Dicts and Sum Shared Keys

Difficulty: Easy · Topic: Core Python & data structures

Daily event counts arrive as one dict per source. Write merge_counts(*dicts): return a new dict with every key from every input; when a key appears in several inputs, add its values up.

Your code runs in CPython on our servers against 5 tests, including hidden ones.

Sample test

merge_counts({'a': 1, 'b': 2}, {'b': 3, 'c': 4})

Expected: {'a': 1, 'b': 5, 'c': 4}

Hints

Hint 1*dicts collects any number of positional arguments into a tuple.
Hint 2out[k] = out.get(k, 0) + v adds to a running total.
Hint 3Counter addition looks perfect, but it drops keys whose total is not positive.

Learn the concepts

More Python problems

All Python problems