Preferred Python idiom for handling non-existing dictionary keys and why?

Alex Martelli aleaxit at yahoo.com
Fri Oct 10 17:44:32 EDT 2003


Skip Montanaro wrote:
   ...
>     % timeit.py -s 'd={}' 'x = d.setdefault("x", [])'
>     1000000 loops, best of 3: 1.82 usec per loop
>     % timeit.py -s 'd={}' 'x = d.get("x") or [] ; d["x"] = x'
>     100000 loops, best of 3: 2.34 usec per loop
> 
> But my way isn't bad enough for me to change. ;-)

Actually, you can still do a bit better w/o using setdefault:

[alex at lancelot pop]$ timeit.py -s'd={}' 'x=d.setdefault("x",[])'
1000000 loops, best of 3: 0.925 usec per loop
[alex at lancelot pop]$ timeit.py -s'd={}' 'x=d.get("x") or []; d["x"]=x'
1000000 loops, best of 3: 1.21 usec per loop
[alex at lancelot pop]$ timeit.py -s'd={}' 'x=d.get("x",[]); d["x"]=x'
1000000 loops, best of 3: 1.13 usec per loop

as d.get takes a second optional argument, you can still save the 'or'.


Alex





More information about the Python-list mailing list