Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Merge a list of dictionaries by key

Group a list of dictionaries by a specified key and merge their fields into combined entries. Conflicting values become lists of unique values in order encountered.

Python practice13 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Given a list of dictionaries and a key name, group the dictionaries by the value at that key. For each group produce a single merged dictionary (excluding the grouping key itself) where: - If a field has the same value across all items in the group, keep it as a scalar. - If a field has different values across the group, collect them into a list of unique values in the order they were encountered. - Skip any input dictionaries that do not contain the grouping key. Return a dictionary that maps each distinct key value to its merged dictionary. This is useful when combining rows of data with a shared identifier and you want to aggregate differing attributes without losing information.

Task

Implement a function that groups dictionaries by a given key and merges other fields, producing a mapping from key value to merged dictionary.

Examples

Basic merge

Input

merge_dicts_by_key([{'id':1,'a':10},{'id':1,'b':20}], 'id')

Output

{1: {'a': 10, 'b': 20}}

Two records share id=1. Fields 'a' and 'b' are merged into the single result for key 1.

Input format

A list of dictionaries and a string key name: (items, key)

Output format

A dictionary mapping each key value to a merged dictionary of the remaining fields.

Constraints

- Items that are not dicts or that don't contain the key should be ignored. - Preserve the order of encountered values when creating lists. - Use only standard Python; aim for O(n * m) where n is number of items and m average fields per item.

Samples

Sample 1

Input

merge_dicts_by_key([{'id':'x','v':1},{'id':'x','v':2},{'id':'y','v':3}], 'id')

Output

{'x': {'v': [1, 2]}, 'y': {'v': 3}}

Key 'x' had two different v values so they are collected into a list; 'y' had a single value.