Home > Backend Development > Python Tutorial > How Can I Efficiently Invert a Dictionary in Python?

How Can I Efficiently Invert a Dictionary in Python?

Susan Sarandon
Release: 2024-12-17 14:00:17
Original
349 people have browsed it

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}
Copy after login

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()}
Copy after login

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()}
Copy after login

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'}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template