Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Invert a Dictionary with Duplicate Values

Create an inverted mapping where each original value maps to the list of keys that referenced it.

Python practice16 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Implement invert_mapping(d) which returns a new dictionary mapping each value found in d to a list of keys that originally pointed to that value. Always produce lists (even if a value had a single key). For deterministic output, the lists of keys must be sorted using the default Python ordering when possible.

Task

Write a function to invert a dictionary so that values become keys and values are lists of original keys (sorted for determinism).

Examples

Values shared by multiple keys

Input

invert_mapping({'a': 1, 'b': 1, 'c': 2})

Output

{1: ['a', 'b'], 2: ['c']}

'a' and 'b' both mapped to 1, so 1 maps to the list ['a', 'b'].

Input format

A dict d with hashable keys and hashable values.

Output format

A dict mapping each original value to a sorted list of keys that had that value.

Constraints

Lists of keys should be sorted for determinism; do not attempt to coerce or merge different types beyond sorting where possible.

Samples

Sample 1

Input

invert_mapping({'a': 1, 'b': 2})

Output

{1: ['a'], 2: ['b']}

Simple inversion where each value is unique.