[dictionary] how to get key by item
Skip Montanaro
skip at pobox.com
Mon Dec 13 20:16:08 EST 2004
Egor> i know how to get item by key
...
Egor> but i wonder how to get key by item
Assuming your dictionary defines a one-to-one mapping, just invert it:
>>> forward = {10 : 50, 2 : 12, 4 : 43}
>>> reverse = dict([(v,k) for (k,v) in forward.iteritems()])
>>> print forward
{10: 50, 4: 43, 2: 12}
>>> print reverse
{50: 10, 43: 4, 12: 2}
That doubles your storage, so you'll have to trade that off against the
speed gain of not having to loop over the entire dictionary.
Skip
More information about the Python-list
mailing list