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]})
You probably want
__missing__which is called ondictwhenever 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: