Menu

Sign in to track your progress and unlock all features.

Theme style

Start learning freeLog in

Problem No 14

Merge dictionaries by summing matching values

Medium

≈ 16 minute session

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.

Code editor
Loading editor…

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.