Home >Backend Development >Python Tutorial >How Do I Reverse a Dictionary's Key-Value Pairs in Python?
Inverting a Dictionary Mapping
Often in programming, we encounter situations where we need to invert a dictionary, essentially flipping the keys and values to create a new dictionary. For instance, we might have a dictionary mapping keys to their corresponding values:
my_map = {'a': 1, 'b': 2}
And desire to create a new dictionary where the values become the keys and vice versa:
inv_map = {1: 'a', 2: 'b'}
To perform this operation in Python, we can utilize comprehension to create a new dictionary with the desired key-value pairs:
Python 3+: inv_map = {v: k for k, v in my_map.items()} Python 2: inv_map = {v: k for k, v in my_map.iteritems()}
The above is the detailed content of How Do I Reverse a Dictionary's Key-Value Pairs in Python?. For more information, please follow other related articles on the PHP Chinese website!