HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Reverse / invert a dictionary mapping

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
invertmappingdictionaryreverse

Problem

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'}

Solution

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

Code Snippets

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

Context

Stack Overflow Q#483666, score: 1538

Revisions (0)

No revisions yet.