You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python根据点分隔字符串递归生成任意层级嵌套字典实现方案

问题根源

原build_final_dict函数硬编码了最多3层嵌套的处理逻辑,没有对路径做通用的逐层遍历,当遇到4层及以上的点分隔路径(比如Document.docOne.extra.number)时,会提前将属性值赋值给中间层键,导致深层嵌套结构生成失败,也无法适配任意深度的嵌套场景。

修复方案

改用通用的路径遍历逻辑,沿着点分隔的键路径逐层向下创建字典,直到抵达路径最后一层再写入属性值,不需要硬编码层级,天然支持任意深度嵌套。

重构后的代码如下:

def build_final_dict(root: dict, key_path: str, attr_path: str, client):
    # 拆分嵌套键,提取Client实例对应的属性名
    key_parts = key_path.split('.')
    target_attr = attr_path.removeprefix('client.')
    current_level = root
    # 遍历路径的非最后一段,逐层创建缺失的嵌套字典
    for part in key_parts[:-1]:
        if part not in current_level:
            current_level[part] = {}
        current_level = current_level[part]
    # 最后一层写入属性值
    current_level[key_parts[-1]] = getattr(client, target_attr)


# 初始化结果字典,遍历映射表构建结构
FINAL_DICT = {}
for map_item in dict_list:
    for path_key, client_attr in map_item.items():
        build_final_dict(FINAL_DICT, path_key, client_attr, client1)

注:如果使用Python3.9以下版本,可将attr_path.removeprefix('client.')替换为attr_path.replace('client.', '', 1),仅替换开头的前缀字符串,避免误替换路径其他位置的同名内容。

运行结果

执行后打印FINAL_DICT可得到完全符合预期的结构:

{
  "nameClient": "Stack",
  "emailClient": "xxxxx@xxxx.com",
  "Document": {
    "typeDocument": "TPS",
    "numberDocument": "22222222",
    "docOne": {
      "number": "11111111",
      "type": "docone type",
      "extra": {
        "number": "doc extra number"
      }
    },
    "docTwo": {
      "number": "doc two number"
    }
  }
}

该实现没有任何层级硬编码,只要是点分隔的路径,不管嵌套多少层都能正确生成对应字典结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 09:06:50