本文介绍了如何将defaultdicts的defaultdict转换为dicts的dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用此答案,我创建了defaultdict
的defaultdict
.现在,我想将深层嵌套的dict对象变成普通的python dict.
Using this answer, I created a defaultdict
of defaultdict
s. Now, I'd like to turn that deeply nested dict object back into an ordinary 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})})})})
我认为这不是正确的解决方案:
I assume this is not the right solution:
import json
regdict = json.loads(json.dumps(defdict))
# {u'one': {u'two': {u'three': {u'four': 5}}}}
此外,此答案是不充分的,因为它不会对嵌套的字典进行递归.
Also, this answer is inadequate since it does not recurse on the nested dict(s).
推荐答案
您可以遍历树,将每个defaultdict
实例替换为由dict理解产生的dict:
You can recurse over the tree, replacing each defaultdict
instance with a dict produced by a dict comprehension:
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}}}}
这篇关于如何将defaultdicts的defaultdict转换为dicts的dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!