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'}
JapanHow it works
country_codes.items()gives each pair as(key, value). The loop unpacks it intocountryandcode.{code: country for ...}is a dict comprehension. It builds a new dictionary with the two parts in the opposite order.- The values must be hashable (strings, numbers, tuples) to become keys. A list cannot be a dictionary key, so a dictionary with list values cannot be inverted this way.
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.