python 2.7 fastest dict acces for missing keys -
python 2.7 fastest dict acces for missing keys -
if d dict, python docs provide method:
dict.get = get(...) d.get(k[,d]) -> d[k] if k in d, else d. d defaults none.
another famous pattern is:
try: d[k]: except: d
but in benchmarks (done timeit), have found next approach best:
if k in d: d[k] else: d
the try/except pattern fastest if no exceptions raised, if no exceptions raised, don't need pattern. need refactor code, written lot of .get()'s, because need squeeze performance on limited system. right or wrong? why try/except pattern recommended when looks it's slowest?
looks d[k] if k in d else d
pattern twice faster .get, @ to the lowest degree usages.
.get
$ python -m timeit -s 'd={}; k=xrange(0,100000)' 'd.get(k)' 10000000 loops, best of 3: 0.0934 usec per loop
if/else
$ python -m timeit -s 'd={}; k=xrange(0,100000)' 'd[k] if k in d else none' 10000000 loops, best of 3: 0.0487 usec per loop
python python-2.7 dictionary
Comments
Post a Comment