The Python Oracle

Reverse / invert a dictionary mapping

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 Reverse / Invert A Dictionary Mapping
00:15 Answer 1 Score 51
00:43 Answer 2 Score 232
00:58 Accepted Answer Score 1505
01:12 Answer 4 Score 209
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/4836...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary #mapping #reverse

#avk47



ACCEPTED ANSWER

Score 1505


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



ANSWER 2

Score 232


Assuming that the values in the dict are unique:

Python 3:

dict((v, k) for k, v in my_map.items())

Python 2:

dict((v, k) for k, v in my_map.iteritems())



ANSWER 3

Score 209


If the values in my_map aren't unique:

Python 3:

inv_map = {}
for k, v in my_map.items():
    inv_map[v] = inv_map.get(v, []) + [k]

Python 2:

inv_map = {}
for k, v in my_map.iteritems():
    inv_map[v] = inv_map.get(v, []) + [k]



ANSWER 4

Score 51


Try this:

inv_map = dict(zip(my_map.values(), my_map.keys()))

(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:

inv_map = dict((my_map[k], k) for k in my_map)

or using python 3.0's dict comprehensions

inv_map = {my_map[k] : k for k in my_map}