你只是在寻找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})
你可以把它放到一个函数中。
>>> 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
或者为了满足您的原始要求,返回一个函数:
>>> 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})
>>>