Created
September 26, 2022 21:01
-
-
Save ZhouYang1993/7400fcff82cf905562b13c05c6ec5830 to your computer and use it in GitHub Desktop.
Reverse Keys and Values of Python Dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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