Brian M. Hunt Brian M. Hunt - 4 months ago 23
Python Question

Python reverse / invert a mapping

Given a dictionary like so:

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


How can one invert this map to get:

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

Answer

For python 2.7+ / 3+:

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