python - 将 dict 转换为 defaultdict

标签 python python-3.x dictionary defaultdict python-collections

以下代码使用 {} 运算符组合两个 defaultdict。

from collections import defaultdict
aa=defaultdict(str)
bb=defaultdict(str)
aa['foo']+= '1'
bb['bar']+= '2'
cc = {**aa,**bb}
type(cc)

但是,正如我们看到的,如果我们运行它,{}运算符返回 dict输入不是 defaultdict类型。

有没有办法转换 dict回到defaultdict?

最佳答案

您可以在调用 defaultdict 时直接使用拆包功能。 . defaultdictdict 的子类,并将这些参数传递给其父级以创建字典,就像它们已传递给 dict 一样.

cc = defaultdict(str, **aa, **bb)
# defaultdict(<class 'str'>, {'bar': '2', 'foo': '1'})

关于python - 将 dict 转换为 defaultdict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51769187/

相关文章:

python - 删除数据框值Python中的第一个日期实例

python - 如何在列表的 “big data”字典上并行化计算?

python - 使用map和lambda来模拟字典理解

python-3.x - python 3 hashlib.sha256().update(newcontent) 似乎不会覆盖旧内容

python - 如何返回一个值,但继续执行

javascript - map.delete(key) 在 map.forEach 期间

python - 如何解析按特定标签 ID 分组的 XML

python - 允许 Argparse 参数的特定值

python - 在 azure 函数中找不到本地模块

python - 如何从 JSON 文件中删除反斜杠