gpt4 book ai didi

python - 如何将 defaultdicts [of defaultdicts] 的 defaultdict 转换为 dicts [of dicts] 的 dict?

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

使用 this answer ,我创建了 defaultdictdefaultdict。现在,我想把那个嵌套很深的 dict 对象变回一个普通的 python dict。

from collections import defaultdict

factory = lambda: defaultdict(factory)
defdict = factory()
defdict['one']['two']['three']['four'] = 5

# defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'one': defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'two': defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'three': defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'four': 5})})})})

我认为这不是正确的解决方案:

import json

regdict = json.loads(json.dumps(defdict))

# {u'one': {u'two': {u'three': {u'four': 5}}}}

另外,this answer是不够的,因为它不会在嵌套的 dict(s) 上递归。

最佳答案

您可以在树上递归,将每个 defaultdict 实例替换为由 dict 理解生成的 dict:

def default_to_regular(d):
if isinstance(d, defaultdict):
d = {k: default_to_regular(v) for k, v in d.items()}
return d

演示:

>>> from collections import defaultdict
>>> factory = lambda: defaultdict(factory)
>>> defdict = factory()
>>> defdict['one']['two']['three']['four'] = 5
>>> defdict
defaultdict(<function <lambda> at 0x103098ed8>, {'one': defaultdict(<function <lambda> at 0x103098ed8>, {'two': defaultdict(<function <lambda> at 0x103098ed8>, {'three': defaultdict(<function <lambda> at 0x103098ed8>, {'four': 5})})})})
>>> default_to_regular(defdict)
{'one': {'two': {'three': {'four': 5}}}}

关于python - 如何将 defaultdicts [of defaultdicts] 的 defaultdict 转换为 dicts [of dicts] 的 dict?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26496831/

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