[英]How to make a dictionary nested in a nested dictionary an OrderedDict (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)
我尝试使用如下所示的列表使用此处的答案:
meta = {'task': [('id', 'text'),
('name', 'text'),
('size',''),
('mode', 'interpolation'),
('overlap', '5'),
('bugtracker', ''),
('created', ''),
('updated', ''),
('start_frame', ''),
('stop_frame', ''),
('frame_filter', '')]}
但这不适用于嵌套在嵌套字典中的字典。 如何将整个字典转换为 OrderedDict,甚至是最里面的嵌套字典?
PS 我觉得这里的答案是我需要的,但我似乎无法弄清楚这里的变量terminal
和lhs
是什么。 如果有人可以对此提供帮助,那也将非常有帮助。
这需要递归:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.