如何将嵌套的OrderedDict转换为dict? [英] how to convert a nested OrderedDict to dict?
本文介绍了如何将嵌套的OrderedDict转换为dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套的 OrderedDict
我想转换为 dict
。应用 dict()
显然只能转换最后一个条目的最外层。
I have a nested OrderedDict
I would like to convert to a dict
. Applying dict()
on it apparently only converts the outermost layer of the last entry.
from collections import OrderedDict
od = OrderedDict(
[
(u'name', u'Alice'),
(u'ID', OrderedDict(
[
(u'type', u'card'),
(u'nr', u'123')
]
)),
(u'name', u'Bob'),
(u'ID', OrderedDict(
[
(u'type', u'passport'),
(u'nr', u'567')
]
))
]
)
print(dict(od))
输出:
{u'name': u'Bob', u'ID': OrderedDict([(u'type', u'passport'), (u'nr', u'567')])}
有没有直接的方法来转换所有的事件?
Is there a direct method to convert all the occurences?
推荐答案
最简单的解决方案是使用json转储并加载
Simplest solution is to use json dumps and loads
from json import loads, dumps
from collections import OrderedDict
def to_dict(input_ordered_dict):
return loads(dumps(input_ordered_dict))
这篇关于如何将嵌套的OrderedDict转换为dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文