Is there a short-circuiting dictionary "get" method?

Duncan Booth duncan.booth at invalid.invalid
Fri Mar 11 05:47:44 EST 2005


Bengt Richter wrote:

> then there's always
> 
>    if 'x' in d: value = d['x']
>    else: value = bsf()
> 
> or
> 
>    try: value = d['x']
>    except KeyError: value = bsf()
> 

Its worth remembering that the first of those two suggestions is also 
faster than using get, so you aren't losing on speed if you write the code 
out in full: choose whichever seems clearest and uses the least contorted 
code.

(The second is the fastest of all if the value is found, but a lot slower 
if the exception gets thrown.)

C:\Python24\Lib>timeit.py -s "d={}" -s "for k in range(1000): d['x%s'%k]=k" 
"value = d.get('x45', 'notfound')"
1000000 loops, best of 3: 0.427 usec per loop

C:\Python24\Lib>timeit.py -s "d={}" -s "for k in range(1000): d['x%s'%k]=k" 
"value = d.get('z45', 'notfound')"
1000000 loops, best of 3: 0.389 usec per loop

C:\Python24\Lib>timeit.py -s "d={}" -s "for k in range(1000): d['x%s'%k]=k" 
"if 'x45' in d: value=d['x45']" "else: value='notfound'"
1000000 loops, best of 3: 0.259 usec per loop

C:\Python24\Lib>timeit.py -s "d={}" -s "for k in range(1000): d['x%s'%k]=k" 
"if 'z45' in d: value=d['z45']" "else: value='notfound'"
1000000 loops, best of 3: 0.131 usec per loop

C:\Python24\Lib>timeit.py -s "d={}" -s "for k in range(1000): d['x%s'%k]=k" 
"try: value=d['x45']" "except: value='notfound'"
1000000 loops, best of 3: 0.158 usec per loop

C:\Python24\Lib>timeit.py -s "d={}" -s "for k in range(1000): d['x%s'%k]=k" 
"try: value=d['z45']" "except: value='notfound'"
100000 loops, best of 3: 2.71 usec per loop



More information about the Python-list mailing list