Reverse / invert a dictionary mapping

Brian M. Hunt picture Brian M. Hunt · Jan 27, 2009 · Viewed 472.4k times · Source

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

Answer

SilentGhost picture SilentGhost · Jan 27, 2009

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