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

2024-05-14 03:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字典,我需要订购字典中的嵌套字典

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)

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

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

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

另外,我感觉来自here的答案是我所需要的,但我似乎无法弄清楚变量terminallhs在这里是什么。如果有人能帮上忙,那也会很有帮助


Tags: textnameidtasksize字典modeframe
1条回答
网友
1楼 · 发布于 2024-05-14 03:51:15

这需要递归:

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)

相关问题 更多 >