Dictionary Management
Data Structures
Python Programming
Coding Tutorials
Key-Value Pairs

Reverse / invert a dictionary mapping

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Inverting a dictionary means turning its values into keys and its keys into values. That sounds simple, but the right solution depends on whether the original values are unique. If they are not unique, a naive inversion will lose data.

The Simple Case: Values Are Unique

If every value appears only once and every value is hashable, inversion is straightforward.

python
1original = {"a": 1, "b": 2, "c": 3}
2inverted = {value: key for key, value in original.items()}
3
4print(inverted)

This produces:

python
{1: "a", 2: "b", 3: "c"}

This is the cleanest solution when the mapping is truly one-to-one.

The Real Problem: Duplicate Values

If the original dictionary contains duplicate values, a direct inversion will overwrite earlier keys.

python
1original = {"a": 1, "b": 1, "c": 2}
2inverted = {value: key for key, value in original.items()}
3
4print(inverted)

The result will only keep one of the keys for value 1, because dictionary keys must be unique.

That means direct inversion is only correct when the original values are unique.

Safe Inversion for Non-Unique Values

If multiple keys share the same value, the inverted mapping should usually store a list of original keys.

python
1original = {"a": 1, "b": 1, "c": 2}
2inverted = {}
3
4for key, value in original.items():
5    inverted.setdefault(value, []).append(key)
6
7print(inverted)

This produces:

python
{1: ["a", "b"], 2: ["c"]}

Now no information is lost.

defaultdict Makes Grouping Cleaner

For grouped inversion, collections.defaultdict is often more readable than setdefault.

python
1from collections import defaultdict
2
3original = {"a": 1, "b": 1, "c": 2}
4inverted = defaultdict(list)
5
6for key, value in original.items():
7    inverted[value].append(key)
8
9print(dict(inverted))

This is a good default when you already know collisions are possible.

Values Must Be Hashable

When you invert a dictionary, the old values become the new keys. That means the old values must be hashable.

This works:

python
original = {"x": (1, 2), "y": (3, 4)}
inverted = {value: key for key, value in original.items()}
print(inverted)

This does not work:

python
original = {"x": [1, 2], "y": [3, 4]}

Lists cannot be dictionary keys because they are mutable and unhashable.

So before inverting, ask two questions:

  • are the values unique
  • are the values hashable

Those two checks determine which inversion strategy is valid.

Inverting Multi-Value Mappings Intentionally

Sometimes the grouped form is actually the goal, not just a workaround. For example, if you have a mapping from student to grade and you want grade to students:

python
1from collections import defaultdict
2
3grades = {"Ana": "A", "Ben": "B", "Cara": "A"}
4by_grade = defaultdict(list)
5
6for student, grade in grades.items():
7    by_grade[grade].append(student)
8
9print(dict(by_grade))

This is more of a regrouping transformation than a strict mathematical inverse, but it is often what applications really need.

Preserve Ordering When It Matters

Modern Python dictionaries preserve insertion order, but once you invert or group values, the resulting order depends on the iteration order of the original mapping and how you collect collisions.

If ordering matters for output or tests, make that explicit:

  • sort the keys
  • sort the grouped lists
  • document the ordering rule

Otherwise, the logic may be correct while the presentation remains unstable.

Common Pitfalls

The most common pitfall is using the one-line inversion for a dictionary whose values are not unique. That silently drops data.

Another mistake is forgetting that the original values must be hashable if they are going to become dictionary keys.

A third issue is assuming “invert” always means a one-to-one mapping. In many real cases, grouped inversion into lists is the correct answer.

Finally, developers sometimes blame Python when a direct inversion loses entries, but that behavior is just the normal rule that dictionary keys are unique.

Summary

  • Use a dictionary comprehension to invert a mapping only when the original values are unique and hashable.
  • If values repeat, group the original keys under each value instead of overwriting them.
  • 'defaultdict(list) is a clean tool for grouped inversion.'
  • Always check whether the values can legally become dictionary keys.
  • The right inversion strategy depends on the shape of the original data, not just on the syntax.

Course illustration
Course illustration

All Rights Reserved.