[dictionary] how to get key by item

Keith Dart kdart at kdart.com
Tue Dec 14 08:15:24 CET 2004


Skip Montanaro wrote:
>     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

But beware that all the items in the original dictionary must be 
hashable. The example shows just integers, so I assume they are in this 
case. But generally, this may not work.



-- 
                            \/ \/
                            (O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <kdart at kdart.com>
vcard: <http://www.kdart.com/~kdart/kdart.vcf>
public key: ID: F3D288E4       URL: <http://www.kdart.com/~kdart/public.key>
============================================================================



More information about the Python-list mailing list