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.
- The inputs must not be changed.
- Keep every key, including ones whose total is 0 or negative.
- With no inputs, return an empty dict.
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 2
out[k] = out.get(k, 0) + v adds to a running total.Hint 3
Counter addition looks perfect, but it drops keys whose total is not positive.Learn the concepts
- Counter, defaultdict and deque · 6 min read. Count, group and keep the last N with the collections module, and the traps in each.
- Functions, *args, **kwargs and closures · 8 min read. Every kind of parameter, closures that remember state, nonlocal and late binding.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Zip Columns into Records · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium