Home > Backend Development > Python Tutorial > How Can I Invert a Dictionary's Key-Value Pairs in Python?

How Can I Invert a Dictionary's Key-Value Pairs in Python?

Mary-Kate Olsen
Release: 2024-12-26 09:39:15
Original
984 people have browsed it

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

The goal is to create an inverted dictionary where the values become keys and the keys become values:

inv_map = {1: 'a', 2: 'b'}
Copy after login

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

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

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!

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