gpt4 book ai didi

python - 如何从字典中构造一个 defaultdict?

转载 作者:IT老高 更新时间:2023-10-28 21:44:59 27 4
gpt4 key购买 nike

如果我有 d=dict(zip(range(1,10),range(50,61))) 我该如何构建 collections.defaultdict dict 的?

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

最佳答案

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)))

或者给定一个字典d:

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

关于python - 如何从字典中构造一个 defaultdict?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7539115/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com