Python reverse / invert a mapping


Question

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' }
1
564
7/15/2019 2:57:52 AM

Accepted Answer

For Python 2.7.x

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

For Python 3+:

inv_map = {v: k for k, v in my_map.items()}
792
10/14/2016 4:21:01 PM

Assuming that the values in the dict are unique:

dict((v, k) for k, v in my_map.iteritems())

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon