[dictionary] how to get key by item

Ola Natvig ola.natvig at infosense.no
Tue Dec 14 04:01:50 EST 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

If some keys has the same value as the item this will cause problems 
because keys in your result dictionary can be overwritten. Could it be a 
  option to build the result dictionary as a dictionary with the values 
as the keys, and lists of keys as the value. Perhaps you need to use a 
loop for this.

-- 
--------------------------------------
  Ola Natvig <ola.natvig at infosense.no>
  infoSense AS / development



More information about the Python-list mailing list