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' }
EDITOR NOTE: map
changed to my_map
to avoid conflicts with the built-in function, map
. Some comments may be affected below.
Fast functional solution for non-bijective maps (values not unique):
In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.
Unfortunately the values have to be sortable, the sorting is required by groupby.
Try this:
(Note that the Python docs on dictionary views explicitly guarantee that
.keys()
and.values()
have their elements in the same order, which allows the approach above to work.)Alternatively:
or using python 3.0's dict comprehensions
Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))
Another, more functional, way:
if the items are not unique try this:
For Python 2.7.x
For Python 3+: