[dictionary] how to get key by item

Roy Smith roy at panix.com
Tue Dec 14 02:53:11 CET 2004


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

Well, you *do* loop over the entire dictionary, but you only do it once, 
when you create the reverse dict.  If you are only going to do a single 
lookup, it's no gain, but if you amortize the cost over many lookups, 
it's almost certainly a big win.

This raises an interesting question.  Let's assume that you add all the 
entries to the dictionary before you do any lookups, and you then need 
to lookup things up in both directions.  Which is faster, to 
simultaneously build both the forward and reverse dicts, or to just 
build the forward one and when you're done doing that, build the reverse 
one in a single shot with the above list comprehension?

BTW, does Python really build the intermediate list and throw it away 
after using it to initialize the dictionary, or is it smart enough to 
know that it doesn't really need to build the whole list in memory?



More information about the Python-list mailing list