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
Mary-Kate OlsenOriginal
2024-12-26 09:39:15981browse

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}

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

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

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

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

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!

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