Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse / invert a dictionary mapping

Given a dictionary like so:

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

How can one invert this map to get:

inv_map = {1: 'a', 2: 'b'} 
like image 532
Brian M. Hunt Avatar asked Jan 27 '09 14:01

Brian M. Hunt


People also ask

How do you reverse a dictionary?

1) Using OrderedDict() and items() method Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.

How do you reverse a dictionary in a for loop in python?

Use items() to Reverse a Dictionary in Python Reverse the key-value pairs by looping the result of items() and switching the key and the value. The k and v in the for loop stands for key and value respectively.

What does .items do in python?

The items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs.


1 Answers

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()} 
like image 57
SilentGhost Avatar answered Oct 29 '22 23:10

SilentGhost