Reverse / invert a dictionary mapping Reverse / invert a dictionary mapping python python

Reverse / invert a dictionary mapping


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


Assuming that the values in the dict are unique:

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


If the values in my_map aren't unique:

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


matomo