Reverse / invert a dictionary mapping
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 Question
00:22 Accepted answer (Score 1389)
00:39 Answer 2 (Score 214)
00:58 Answer 3 (Score 189)
01:20 Answer 4 (Score 52)
01:36 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 Question
00:22 Accepted answer (Score 1389)
00:39 Answer 2 (Score 214)
00:58 Answer 3 (Score 189)
01:20 Answer 4 (Score 52)
01:36 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}