[dictionary] how to get key by item

Aahz aahz at pythoncraft.com
Tue Dec 14 00:23:53 EST 2004


In article <mailman.7665.1102986976.5135.python-list at python.org>,
Skip Montanaro  <skip at pobox.com> wrote:
>
>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.

To be precise, it doubles the storage of the *dictionary*, but it does
*NOT* double the storage of the keys and items.  Depending on how big
those are, the cost of building a second dict might be mostly lost in the
noise.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis



More information about the Python-list mailing list