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
Mary-Kate OlsenOriginal
2024-12-18 07:32:13412browse

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()}

Python 2:

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

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!

Statement:
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