有序字典的有序字典需要转换为字典的字典

Ordered dictionary of ordered dictionaries need to be converted to dictionary of dictionaries

我有一个数据集,可能有n级有序字典的有序字典,现在我需要将它们全部转换成普通字典,除了递归搜索和转换之外,还有更简单的方法吗?

from collections import OrderedDict
an=OrderedDict([('method', 'constant'), ('data', '1.225')])

aw=OrderedDict([('method', 'constant'), ('data', OrderedDict([('1.225','777')]))])

print dict(an)
print dict(aw)
{'data': '1.225', 'method': 'constant'}
{'data': OrderedDict([('1.225', '777')]), 'method': 'constant'}

可能不会。您可以将递归算法包装在一个函数中:

from collections import OrderedDict

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

aw = OrderedDict([('method', 'constant'), ('data', OrderedDict([('1.225','777')]))])
res = ordered_to_regular_dict(aw)

# {'data': {'1.225': '777'}, 'method': 'constant'}