dictionaries - returning a key from a value

Fredrik Lundh fredrik at pythonware.com
Fri Sep 1 10:02:55 EDT 2006


bearophileHUGS at lycos.com wrote:

> keys = [key for key in sampledict if sampledict[key] == '1974']
>
> Or better, given:
>
> sampledict = {'the Holy Grail':1975, 'Life of Brian':1979,
>              'Party Political Broadcast':1974,'Mr. Neutron':1974,
>              'Hamlet':1974, 'Light Entertainment War':1974}
>
> keys = [key for key,year in sampledict.iteritems() if year == 1974]

better in what sense?

timeit -s "from test import sampledict" "keys = [key for key in sampledict if sampledict[key] == 
1974]"
100000 loops, best of 3: 2.27 usec per loop

timeit -s "from test import sampledict" "keys = [key for key,year in sampledict.iteritems() if year 
== 1974]"
100000 loops, best of 3: 2.56 usec per loop

</F> 






More information about the Python-list mailing list