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

标签 python python-2.7 dictionary collections

使用 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/

相关文章:

python - 我怎样才能让 pip 知道我对 python 3.4 的包感兴趣?

python - 什么范围函数对 Python 列表有作用?

python - Python类成员查找的底层机制

arrays - 不确定如何访问 firebase 数据库中的每个值

python - 如何使用scrapy获取匹配的行号

python - 如何从 Odoo v10 中删除此 Controller 错误

python - 如何通过字符串匹配加速 Pandas 行过滤?

python - 枚举列表中的唯一字符串

python - 使用字典查找文件中单词出现的行号

python - @staticmethod 和 @property