如何使嵌套在嵌套字典中的字典成为 OrderedDict (Python)?

时间:2021-07-19 14:50:26

标签: python dictionary

我有以下字典,我需要对字典中的嵌套字典进行排序。

meta = {'task': {'id': 'text',
        'name': 'text',
        'size': '',
        'mode': 'interpolation',
        'overlap': '5',
        'bugtracker': '', 
        'created': '',
        'updated': '',
        'start_frame': '',
        'stop_frame': '',
        'frame_filter': '',
        'labels': {'label': {'name': 'text',
            'color': 'text',
            'attributes': {'attributes': {'name': 'text',
                         'mutable': 'False',
                         'input_type': 'text',
                         'default_value': '',
                         'values': '',}}}}}}
meta = collections.OrderedDict(meta)

我尝试使用来自 Typer 的答案使用如下所示的列表:

meta = {'task': [('id', 'text'),
        ('name', 'text'),
        ('size',''),
        ('mode', 'interpolation'),
        ('overlap', '5'),
        ('bugtracker', ''), 
        ('created', ''),
        ('updated', ''),
        ('start_frame', ''),
        ('stop_frame', ''),
        ('frame_filter', '')]}

但这不适用于嵌套在嵌套字典中的字典。如何将整个字典转换为 OrderedDict,甚至是最内层的嵌套字典?

附言我有一种感觉,here 的答案正是我所需要的,但我似乎无法弄清楚这里的变量 terminallhs 是什么。如果有人能对此提供帮助,那也将非常有帮助。

1 个答案:

答案 0 :(得分:1)

这需要递归:

def convert(obj):
    if isinstance(obj, dict):
        return OrderedDict((k, convert(v)) for k, v in obj.items())
    # possibly, if your data contains lists
    if isinstance(obj, list):
        return [*map(convert, obj)]
    return obj

meta = convert(meta)
相关问题