Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Merge dictionaries by summing matching values

Combine multiple dictionaries into one by summing values for matching keys.

Python practice16 minDictionaries & SetsIntermediateLast updated March 18, 2026

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}

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 1

Input

merge_sum([{'x': 10}, {'y': 5}, {'x': 2, 'z': 1}])

Output

{'x': 12, 'y': 5, 'z': 1}

x occurs twice and is summed (10 + 2 = 12); y and z appear once.