Feed on
Posts
Comments

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.


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

One Response to “how to invert a dictionary in python”

  1. on 14 Jun 2007 at 12:09 am Henry

    Another (clearer?) way is to run

    b = dict((value, key) for key,value in a.iteritems())

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.