Reverse dictionnary
François Pinard
pinard at iro.umontreal.ca
Fri Nov 15 08:58:01 EST 2002
[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.
As others told you already, this is not always possible. Values should
be immutable (or more precisely: hashable) and all unique.
But given the proper pre-conditions, list comprehension might be the most
legible way to go. Still, I wonder if one would not gain some speed by
avoiding Python loops, like this maybe:
def reverse(dictionary):
pair = zip(*dictionary.items())
return dict(zip(pair[1], pair[0]))
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list