dictionaries - returning a key from a value

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Sep 1 10:26:50 EDT 2006


Fredrik Lundh:
> better in what sense?

With better I may mean faster, or needing less memory, or requiring a
shorter code, or other things. It depends on many things, related to
the program I am creating.

Thank you for the timings, you are right, as most times. Sometimes I am
wrong, but I try to suggest correct things and I usually try to be
helpful, as you do too, and I am learning still.
I have done timings for other things, but not for this one :-)
I have assumed that the version using iteritems (I think that in Py3.0
items will become iteritems) is the faster in that situation (but your
test shows that I was wrong).

This seems to require one hash access, plus the iteration:
... for key in sampledict if sampledict[key] ...

This seems to require just the iteration plus the key,year tuple
creation:
... for key,year in sampledict.iteritems() if year ...

I have assumed that the hash access + an interation is slower, but
maybe the tuple object creation is slow(er) too. As usual to know
what's better in a given Python version you have to test it.

Bye,
bear hugs,
bearophile




More information about the Python-list mailing list