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
Patricia ArquetteOriginal
2024-12-26 20:59:11904browse

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}

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

inv_map = {1: 'a', 2: 'b'}

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

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!

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