Are you just looking 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 can put this in 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
To satisfy your initial requirements, return the function:
>>> def defaultdictinitfactory(type_):
... def createupdate(*args, **kwargs):
... d = defaultdict(type_)
... d.update(*args, **kwargs)
... return d
... return createupdate
...
>>> f = defaultdictinitfactory(int)
>>> d = f((i, i*i) for i in range(3))
>>> d
defaultdict(<type 'int'>, {0: 0, 1: 1, 2: 4})
>>>
source
share