On 13/02/2007 20.01, Raymond Hettinger wrote: > 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.
But it's the most unreadable too. I'm surprised that defaultdict(int) is slower than the lambda one though. What's the reason? -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list