Reverse / invert a dictionary mapping
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 Reverse / Invert A Dictionary Mapping
00:17 Accepted Answer Score 1479
00:35 Answer 2 Score 231
00:54 Answer 3 Score 203
01:16 Answer 4 Score 54
01:33 Answer 5 Score 49
02:01 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
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 Reverse / Invert A Dictionary Mapping
00:17 Accepted Answer Score 1479
00:35 Answer 2 Score 231
00:54 Answer 3 Score 203
01:16 Answer 4 Score 54
01:33 Answer 5 Score 49
02:01 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}