Invert a Dictionary with Comprehension

Published:
Last updated:
By Jeferson Peter
Python

Basic inversion

students = {"Alice": 1, "Bob": 2, "Charlie": 3}
inverted = {v: k for k, v in students.items()}
print(inverted)

# {1: 'Alice', 2: 'Bob', 3: 'Charlie'}

Handle duplicates (last wins)

grades = {"math": "A", "english": "B", "history": "A"}
inverted = {v: k for k, v in grades.items()}
print(inverted)

# {'A': 'history', 'B': 'english'}

Group duplicates with defaultdict

from collections import defaultdict

grades = {"math": "A", "english": "B", "history": "A"}
inverted = defaultdict(list)

for k, v in grades.items():
    inverted[v].append(k)

print(dict(inverted))

# {'A': ['math', 'history'], 'B': ['english']}

Conclusion

Dictionary comprehensions make inversion simple.
Be mindful when values repeat — by default, the last key wins unless you group them manually.