Home >Backend Development >Python Tutorial >How Can I Efficiently Invert a Dictionary in Python?
Inverting Dictionary Mappings
Given a dictionary, a useful task can be to invert it, meaning that keys and values are swapped. This can be particularly beneficial for situations where accessing values by their original keys is no longer necessary.
Consider a dictionary like:
my_map = {'a': 1, 'b': 2}
Python 3 :
Python 3 introduces a concise method for achieving this inversion using a dictionary comprehension:
inv_map = {v: k for k, v in my_map.items()}
This code iterates through each key-value pair in my_map and reconstructs the inverted dictionary, setting values as keys and keys as values.
Python 2:
For Python 2, a slightly different approach is required:
inv_map = {v: k for k, v in my_map.iteritems()}
my_map.iteritems() is used to retrieve the items as tuples, and then the dictionary comprehension operates in a similar manner as in Python 3.
The resulting inv_map will be:
{1: 'a', 2: 'b'}
This inverted dictionary allows for efficient lookup based on the original values, providing a convenient way to retrieve the associated keys.
The above is the detailed content of How Can I Efficiently Invert a Dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!