3 ms·
If you are predominately adding entries to a dictionary, the standard dict will be faster. Where defaultdict shines is the case where you hit an entry a bunch
by cynwoody 12y ago
If you are predominately adding entries to a dictionary, the standard dict will be faster.
Where defaultdict shines is the case where you hit an entry a bunch of times, but you'd like to automate initializing an entry the first time it is hit.
The most common example is probably the frequency distribution, where the frequency needs to start out zero and be incremented each time a key is seen. Using int or lambda:0 as defaultdict's argument works fine for the simple case. If you want to tabulate more than just the count, e.g. a count and one or more sums, you can pass a constructor that produces an object with an update method, to which you pass whatever your key represents.
Simple microbenchmark: http://pastebin.com/vkacByzp http://pastebin.com/vkacByzp
It appears that defaultdict saves time as well as code for the normal use case.