You need to enable JavaScript to run this app. 如何将多层嵌套dict转换为对应的嵌套OrderedDict结构
优惠活动
大模型
产品
解决方案
定价
更多

如何将多层嵌套dict转换为对应的嵌套OrderedDict结构

嵌套dict转嵌套OrderedDict实现方案

通过递归遍历字典的每一层结构,遇到字典类型就转换为OrderedDict,非字典类型的原值直接返回即可。

from collections import OrderedDict

def to_nested_ordered_dict(input_dict):
    if isinstance(input_dict, dict):
        return OrderedDict(
            (key, to_nested_ordered_dict(value)) 
            for key, value in input_dict.items()
        )
    return input_dict

调用示例:

user_dict = {"a": {"b": {"c":
                              {'d': 'e',
                              'f': 'g',
                              'h': 'i'
                              }}}}

cfg_opts = to_nested_ordered_dict(user_dict)

转换后的cfg_opts与你给出的预期输出完全匹配。

注:Python 3.7及以上版本原生dict默认保留插入顺序,如果你仅需要有序的字典结构可直接使用原生dict,上述代码适用于需要显式生成OrderedDict类型的场景。


内容的提问来源于stack exchange,提问作者Abhishek Inani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 14:03:03