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

How Can I Reverse a Dictionary's Key-Value Mapping in Python?

Mary-Kate Olsen
Release: 2024-12-18 07:32:13
Original
407 people have browsed it

How Can I Reverse a Dictionary's Key-Value Mapping in Python?

Inverting a Dictionary Mapping

Given a dictionary that maps keys to values, there may be a need to invert the mapping, switching the roles of keys and values. Here's how this can be achieved in Python:

Solution:

Python provides a convenient method to invert a dictionary using a dictionary comprehension:

Python 3 :

inv_map = {v: k for k, v in my_map.items()}
Copy after login

Python 2:

inv_map = {v: k for k, v in my_map.iteritems()}
Copy after login

The above is the detailed content of How Can I Reverse a Dictionary's Key-Value Mapping 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