【问题标题】:Ordered dictionary of ordered dictionaries need to be converted to dictionary of dictionaries有序词典的有序词典需要转换为词典的词典
【发布时间】:2019-01-28 16:50:16
【问题描述】:

我有一个数据集,可能有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'}

【问题讨论】:

    标签: python dictionary recursion ordereddictionary


    【解决方案1】:

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

    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'}
    

    【讨论】:

    • 当你又打了我一次,我猜我会删除:p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    相关资源
    最近更新 更多