Home / Python / Example programs / Dictionaries and sets

Python program: Swap keys and values

Turn a {key: value} dictionary into {value: key}.

The code

codes = {"BNE": "Brisbane", "SYD": "Sydney", "MEL": "Melbourne"}
city_to_code = {city: code for code, city in codes.items()}
print(city_to_code["Sydney"])

# when values repeat, collect the keys in lists
team = {"Sita": "data", "Leo": "web", "Mia": "data"}
by_team = {}
for person, t in team.items():
    by_team.setdefault(t, []).append(person)
print(by_team)

Output

SYD
{'data': ['Sita', 'Mia'], 'web': ['Leo']}

How it works

A dictionary comprehension swaps each pair. If several keys share a value, a plain swap would lose some, so group them into lists instead.

Python features used

Learn the ideas behind it in the free lesson Dictionaries & Sets.