Are you just looking for defaultdict.update
?
>>> from collections import defaultdict
>>> thing = defaultdict(int)
>>> thing.update((i, i*i) for i in range(3))
>>> thing
defaultdict(<type 'int'>, {0: 0, 1: 1, 2: 4})
You could put this into a function.
>>> def initdefaultdict(type_, *args, **kwargs):
... d = defaultdict(type_)
... d.update(*args, **kwargs)
... return d
...
>>> thing = initdefaultdict(int, ((i, i+10) for i in range(3)))
>>> thing
defaultdict(<type 'int'>, {0: 10, 1: 11, 2: 12})
>>> thing[3]
0
Or to satisfy your original requirements, return a function:
>>> def defaultdictinitfactory(type_): # this is your "foo"
... def createupdate(*args, **kwargs):
... d = defaultdict(type_)
... d.update(*args, **kwargs)
... return d
... return createupdate
...
>>> f = defaultdictinitfactory(int) # f is your "thing"
>>> d = f((i, i*i) for i in range(3))
>>> d
defaultdict(<type 'int'>, {0: 0, 1: 1, 2: 4})
>>>
thing
andfoo
and why shouldthing
return 0? – Merseything((i, i*i) for i in range(3))
should return adefaultdict
instance. I will edit the question to make that clearer – Guiana-1
made me think it was a list rather than a missing index. If you wanted adefault_factory
that would do this, I don't think it could be done, because (from the docs) "The default factory is called without arguments to produce a new value when a key is not present, in getitem only." – Mersey