how to invert a dictionary in python
October 3rd, 2006 by Lawrence David
inverting a dictionary in python – that is, index it’s keys using it’s values – requires only one line of code:
dict(map(lambda item:(item[1],item[0]),my_dict.items()))
for instance, the dictionary a:
>>> a = dict()
>>> a['me'] = 5
>>> a['you'] = 5
>>> a['her'] = 6
>>> a['him'] = 245
>>> print a
{‘me’: 5, ‘you’: 5, ‘him’: 245, ‘her’: 6}
can easily be inverted to form the dictionary b:
>>> b = dict(map(lambda item: (item[1],item[0]),a.items()))
>>> print b
{5: ‘you’, 6: ‘her’, 245: ‘him’}
note that, of course, entries with duplicate values end up overwriting one another when used as keys.

Another (clearer?) way is to run
b = dict((value, key) for key,value in a.iteritems())