I encountered the following idiom in some OpenERP module recently:
some_dict['key'] = some_dict.get('key', {})
It struck me as an unusual way of setting a default value in a dictionary. So I investigated a bit to compare the performance of the construct compared to other ways of doing the same thing, in order to check if what I would have done (f2 below) was the most efficient way in addition to be the (in my opinion, at least) most readable. I used the timeit module and a few different dictionaries in case the presence of the key influenced the performance of the operation:
import timeit def f1(d): d['value'] = d.get('value', {}) def f2(d): if 'value' not in d: d['value'] = {} def f3(d): d.setdefault('value', {}) if __name__ == '__main__': for d in ('{}', "{'a': None, 'b': None}", "{'a': None, 'b': None, 'value': None}"): print d for i in (1, 2, 3): print "f%d" % i t = timeit.Timer('f%d(d)' % i, 'from __main__ import f1, f2, f3; d = %s' % d) print t.repeat()
With my local version (python 2.7.3), f1 is always the slowest, closely followed by f3, and the readable explicit version (f2) also runs 2x faster.
Leave a comment