我有一个嵌套的 OrderedDict
我想转换成一个 dict
。在其上应用 dict()
显然只会转换最后一个条目的最外层。
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')])}
是否有直接的方法来转换所有的出现?
最佳答案
最简单的解决方案是使用 json 转储和加载
from json import loads, dumps
from collections import OrderedDict
def to_dict(input_ordered_dict):
return loads(dumps(input_ordered_dict))
注意:以上代码适用于 json 已知为可序列化对象的字典。可以找到默认对象类型的列表 here
因此,如果有序字典不包含特殊值,这应该足够了。
编辑:根据评论,让我们改进上面的代码。比方说,input_ordered_dict
可能包含默认情况下无法由 json 序列化的自定义类对象。
在这种情况下,我们应该将 json.dumps
的 default
参数与我们的自定义序列化程序一起使用。
(例如):
from collections import OrderedDict as odict
from json import loads, dumps
class Name(object):
def __init__(self, name):
name = name.split(" ", 1)
self.first_name = name[0]
self.last_name = name[-1]
a = odict()
a["thiru"] = Name("Mr Thiru")
a["wife"] = Name("Mrs Thiru")
a["type"] = "test" # This is by default serializable
def custom_serializer(obj):
if isinstance(obj, Name):
return obj.__dict__
b = dumps(a)
# Produces TypeError, as the Name objects are not serializable
b = dumps(a, default=custom_serializer)
# Produces desired output
这个例子可以进一步扩展到更大的范围。我们甚至可以根据需要添加过滤器或修改值。只需将 else 部分添加到 custom_serializer
函数
def custom_serializer(obj):
if isinstance(obj, Name):
return obj.__dict__
else:
# Will get into this if the value is not serializable by default
# and is not a Name class object
return None
在自定义序列化程序的情况下,顶部给出的函数应该是:
from json import loads, dumps
from collections import OrderedDict
def custom_serializer(obj):
if isinstance(obj, Name):
return obj.__dict__
else:
# Will get into this if the value is not serializable by default
# and is also not a Name class object
return None
def to_dict(input_ordered_dict):
return loads(dumps(input_ordered_dict, default=custom_serializer))
关于python - 如何将嵌套的 OrderedDict 转换为字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054003/