Fast constant functions for Py2.5's defaultdict()

Raymond Hettinger python at rcn.com
Tue Feb 13 14:01:45 EST 2007


FWIW, here are three ways of writing constant functions for
collections.defaultdict():

  d = defaultdict(int)       # slowest way; works only for zero
  d = defaultdict(lambda: 0)   # faster way; works for any constant
  d = defaultdict(itertools.repeat(0).next)    # fastest way; works
for any constant

Another approach is to use the __missing__ method for dictionary
subclasses:

  class zerodict (dict):
      def __missing__ (self, key):
          return 0               # fast on initial miss, but slow on
non-misses; works for any constant

The itertools.repeat(const).next approach wins on speed and
flexibility.


Raymond




More information about the Python-list mailing list