Reverse dictionnary

David Brown david at no.westcontrol.spam.com
Fri Nov 15 06:29:27 EST 2002


"Julien Barbot" <barbot at shfj.cea.fr> wrote in message
news:nkz4rajw3ln.fsf at pinel.shfj.cea.fr...
> Hi,
> Does "reverse dictionnary" exists in python ?
> I would like to get a value with the key, and to get the key with the
value
> For example:
> d1 = {1:"str1", 2:"str2" }
>
> d1.getvalue(1) give me "str1"
> and
> g1.getkey("str1") give me 1
>
> With the result given as fast as normal dictionnaries.
>
> If this does not exists, I will simply do two dictionnaries, one with
> the integer as keys and the strings as values and the other one with
> the strings as keys and the intergers as values.
>
>
> Thanks for your help.
> --
> Julien Barbot

Having the same problem once, I used the following function.  I guess it's a
common enough situation, so maybe there are better ideas?

def invDict(d) :
    "Inverts the key, value relationship in a dictionary"
    return dict([(a, b) for (b, a) in d.items()])





More information about the Python-list mailing list