Search code examples
pythoncollectionslambdadefaultdict

Using the key in collections.defaultdict


collections.defaultdict is great. Especially in conjunction with lambda:

>>> import collections
>>> a = collections.defaultdict(lambda : [None,None])
>>> a['foo']
[None, None]

Is there a way to use the key given (e.g. 'foo') in the lambda? For example (doesn't work):

>>> a = collections.defaultdict(lambda : [None]*key)
>>> a[1]
[None]
>>> a[2]
[None, None]
>>> a
defaultdict(<function <lambda> at 0x02984170>, {1: [None], 2: [None, None]})

Solution

  • You probably want __missing__ which is called on dict whenever you try to access an item not present in the dict; the vanilla __missing__ raises an exception, but you could do whatever you like in a subclass:

    class A(dict):
        def __missing__(self, key):
            value = self[key] = [None] * key
            return value