如何从字典中构造默认判决?

如果我有 d=dict(zip(range(1,10),range(50,61))),我怎么能建立一个 collections.defaultdictdict

defaultdict似乎唯一的参数是工厂函数,我必须初始化,然后通过原来的 d和更新的 defaultdict

45557 次浏览

Read the docs:

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

from collections import defaultdict
d=defaultdict(int, zip(range(1,10),range(50,61)))

Or given a dictionary d:

from collections import defaultdict
d=dict(zip(range(1,10),range(50,61)))
my_default_dict = defaultdict(int,d)

You can construct a defaultdict from dict, by passing the dict as the second argument.

from collections import defaultdict


d1 = {'foo': 17}
d2 = defaultdict(int, d1)


print(d2['foo'])  ## should print 17
print(d2['bar'])  ## should print 1 (default int val )

You can create a defaultdict with a dictionary by using a callable.

from collections import defaultdict


def dict_():
return {'foo': 1}


defaultdict_with_dict = defaultdict(dict_)