Problem No 14
Merge dictionaries by summing matching values
Medium≈ 16 minute session
Lesson guide
What this Python exercise practices
Merge dictionaries by summing matching values is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 16 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 16 minutes
Practice path
Summary
Combine multiple dictionaries into one by summing values for matching keys.
Problem statement
Given a list of dictionaries where each dictionary maps keys to numeric values, merge them into a single dictionary. If a key appears in multiple dictionaries, its final value should be the sum of all values seen for that key. Preserve the insertion order based on the first time a key is encountered while processing the input list from left to right.
Task
Implement a function that merges a list of dictionaries by summing values that share the same key, preserving the order in which keys first appear.
Examples
Merge with overlapping keys
Input
merge_sum([{'a': 1, 'b': 2}, {'b': 3, 'c': 4}])
Output
{'a': 1, 'b': 5, 'c': 4}
Explanation
Key 'b' appears in both dictionaries, so its values are summed (2 + 3 = 5). Keys appear in order a, b, c based on first occurrence.
Input format
A list of dictionaries. Example: [{'a':1}, {'b':2, 'a':3}]
Output format
A single dictionary with keys from all input dictionaries and summed numeric values for duplicate keys.
Constraints
- Input is a list (possibly empty) of dictionaries with numeric values. - Return an empty dictionary for an empty input list. - Preserve key order based on first appearance while iterating left-to-right through the list.
Samples
Sample input 0
merge_sum([{'x': 10}, {'y': 5}, {'x': 2, 'z': 1}])
Sample output 0
{'x': 12, 'y': 5, 'z': 1}
Explanation 0
x occurs twice and is summed (10 + 2 = 12); y and z appear once.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.