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.
If the values aren't unique, and you're a little hardcore:
Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over
items()
multiple times.This handles non-unique values and retains much of the look of the unique case.
For Python 3.x, replace itervalues with values. I can't take credit for this... it was suggested by Icon Jack.
Inverse your dictionary:
We may also reverse a dictionary with duplicate keys using
defaultdict
:See here:
Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.
For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value