简体   繁体   中英

How to make a dictionary nested in a nested dictionary an OrderedDict (Python)?

I have the following dictionary and I require the nested dictionaries within the dictionary to be ordered.

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)

I tried using a list as shown below using the answer from here :

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

But this does not work for dictionaries nested within a nested dictionary. How can I convert the entire dictionary to be an OrderedDict, even the innermost nested dictionaries?

PS I have a feeling the answer from here is what I need but I cannot seem to figure out what the variables terminal and lhs are here. If anyone can help with this, that would also be very helpful.

This calls for recursion:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM