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

How Do I Reverse a Dictionary's Key-Value Pairs in Python?

Patricia Arquette
Release: 2024-12-26 20:59:11
Original
899 people have browsed it

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

And desire to create a new dictionary where the values become the keys and vice versa:

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

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

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!

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