Reverse dictionnary

François Pinard pinard at iro.umontreal.ca
Fri Nov 15 09:55:31 EST 2002


[François Pinard]

> [Julien Barbot]

> > Does "reverse dictionnary" exists in python ?  I would like to get a
> > value with the key, and to get the key with the value.

> [...] like this maybe:

>     def reverse(dictionary):
>         pair = zip(*dictionary.items())
>         return dict(zip(pair[1], pair[0]))

I withdraw the above, because, as indirectly suggested by others:

    dict(zip(dictionary.itervalues(), dictionary.iterkeys()))

is likely clearer and better.  Or if you want to spare the keyboard a bit:

    dict(zip(dictionary.itervalues(), dictionary))

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list