Given a dictionary likeso:
map = { 'a': 1, 'b':2 }
How can one invert this map to get:
inv_map = { 1: 'a', 2: 'b' }
Given a dictionary likeso:
map = { 'a': 1, 'b':2 }
How can one invert this map to get:
inv_map = { 1: 'a', 2: 'b' }
Try this :
inv_map = dict(zip(map.values(), map.keys()))
or alternatively
inv_map = dict((map[k], k) for k in map)
or using python 3.0's dict comprehensions
inv_map = {map[k] : k for k in map}
Assuming that the values in the dict are unique:
dict((v,k) for k, v in map.iteritems())
If the values in map
aren't unique:
for k, v in map.iteritems():
inv_map[v] = inv_map.get(v, [])
inv_map[v].append(k)
Or if the values aren't unique and you're a little harcore:
inv_map = \
dict( \
(v, [k for (k, xx) in filter(lambda (key, value): value == v, map.items())]) \
for v in set(map.values()))