Home >Backend Development >Python Tutorial >How Can I Invert a Dictionary's Key-Value Pairs in Python?
Inverting a Dictionary Mapping
Given a dictionary with key-value pairs, such as:
my_map = {'a': 1, 'b': 2}
The goal is to create an inverted dictionary where the values become keys and the keys become values:
inv_map = {1: 'a', 2: 'b'}
Solution
In Python 3 and above, this can be achieved using a dictionary comprehension:
inv_map = {v: k for k, v in my_map.items()}
Here, the items() method returns a list of key-value tuples, and the dictionary comprehension iterates over these tuples to create a new dictionary with inverted keys and values.
For Python 2, the iteritems() method can be used instead:
inv_map = {v: k for k, v in my_map.iteritems()}
The above is the detailed content of How Can I Invert a Dictionary's Key-Value Pairs in Python?. For more information, please follow other related articles on the PHP Chinese website!