PythonMastery

Invert a dictionary in Python

Swap the keys and values of a dictionary with a dict comprehension, and what to do when two keys share the same value.

Inverting a dictionary makes each value a key and each key a value. It is useful for reverse lookups, such as finding a country from its code.

The program

python
country_codes = {"India": "IN", "Japan": "JP", "Brazil": "BR"}

code_to_country = {code: country for country, code in country_codes.items()}

print(code_to_country)
print(code_to_country["JP"])
output
{'IN': 'India', 'JP': 'Japan', 'BR': 'Brazil'}
Japan

How it works

When values repeat

Keys must be unique, but values do not have to be. If two keys have the same value, the simple version keeps only the last one and loses the others without any error:

python
grades = {"Ada": "A", "Linus": "B", "Grace": "A", "Alan": "C"}

print({g: name for name, g in grades.items()})

by_grade = {}
for name, g in grades.items():
    by_grade.setdefault(g, []).append(name)
print(by_grade)
output
{'A': 'Grace', 'B': 'Linus', 'C': 'Alan'}
{'A': ['Ada', 'Grace'], 'B': ['Linus'], 'C': ['Alan']}

The second version maps each value to a list of keys, so nothing is lost. setdefault(g, []) returns the list for g, and creates an empty one first if g is not there yet.

Learn the idea: Dictionaries, Comprehensions: Lists, Dicts, Sets, Generators