Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created September 26, 2022 21:01
Show Gist options
  • Save ZhouYang1993/7400fcff82cf905562b13c05c6ec5830 to your computer and use it in GitHub Desktop.
Save ZhouYang1993/7400fcff82cf905562b13c05c6ec5830 to your computer and use it in GitHub Desktop.
Reverse Keys and Values of Python Dictionaries
cities = {'London': 'UK', 'Tokyo': 'Japan', 'New York': 'US'}
# Method 1
reversed_cities = {v: k for k, v in cities.items()}
print(reversed_cities)
# {'UK': 'London', 'Japan': 'Tokyo', 'US': 'New York'}
# Method 2
reversed_cities = dict(zip(cities.values(), cities.keys()))
print(reversed_cities)
# Method 3
reversed_cities = dict(map(reversed, cities.items()))
print(reversed_cities)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment