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

递归构建Python字典路径时出现名称重复问题求助

问题描述

原始Python字典:

a = {'name': 'Kestral',
     'children': [
         {'name': 'Burtree Lane',
          'children': [
              {'name': 'ARCHIVE', 
               'children': []},
              {'name': 'Development',
               'children': [
                   {'name': 'Fee Proposals',
                    'children': []}]}]}]}

期望生成的字典结构(每个节点新增folder字段,值为从根到当前节点的层级路径):

{'name': 'Kestral',
     'folder': 'Kestral',
     'children': [
         {'name': 'Burtree Lane',
          'folder': 'Kestral/Burtree Lane',
          'children': [
              {'name': 'ARCHIVE',
               'folder': 'Kestral/Burtree Lane/ARCHIVE',
               'children': []},
              {'name': 'Development',
               'folder': 'Kestral/Burtree Lane/Development',
               'children': [
                   {'name': 'Fee Proposals',
                    'folder': 'Kestral/Burtree Lane/Development/Fee Proposals',
                    'children': []}]}]}]}

现有递归代码:

def build_structured_dict(data, parent_path="/"):
  new_dict = {
      "name": data["name"],
      "folder": f"{parent_path}{data['name']}" if parent_path else data["name"],
      "children": [],
  }
  for child in data["children"]:
    child_path = f"{parent_path}{data['name']}" if parent_path else ""
    new_dict["children"].append(build_structured_dict(child, f"{child_path}/{child['name']}"))
  return new_dict

运行后出现folder字段名称重复的错误结果:

{'name': 'Kestral',
     'folder': '/Kestral',
     'children': [{
         'name': 'Burtree Lane',
         'folder': '/Kestral/Burtree LaneBurtree Lane',
         'children': [{
             'name': 'ARCHIVE',
             'folder': '/Kestral/Burtree LaneBurtree Lane/ARCHIVEARCHIVE',
             'children': []},
            {'name': 'Development',
             'folder': '/Kestral/Burtree LaneBurtree Lane/DevelopmentDevelopment',
             'children': [{
                 'name': 'Fee Proposals',
                 'folder': '/Kestral/Burtree LaneBurtree Lane/DevelopmentDevelopment/Fee ProposalsFee Proposals',
                 'children': []}]}]}]}
解决方案

错误原因

递归传递parent_path时,错误地将当前子节点的name提前拼接到路径中,导致下一层递归生成folder字段时,会再次拼接该子节点的name,最终出现重复。

修正后的代码

def build_structured_dict(data, parent_path=""):
    # 构建当前节点的完整路径:有父路径则拼接,无则直接用当前节点名称
    folder_path = f"{parent_path}/{data['name']}" if parent_path else data['name']
    new_dict = {
        "name": data["name"],
        "folder": folder_path,
        "children": [],
    }
    for child in data["children"]:
        # 将当前节点的完整路径作为子节点的父路径传递
        new_dict["children"].append(build_structured_dict(child, folder_path))
    return new_dict

验证结果

调用build_structured_dict(a)后,得到符合预期的输出:

{'name': 'Kestral',
 'folder': 'Kestral',
 'children': [{'name': 'Burtree Lane',
               'folder': 'Kestral/Burtree Lane',
               'children': [{'name': 'ARCHIVE',
                             'folder': 'Kestral/Burtree Lane/ARCHIVE',
                             'children': []},
                            {'name': 'Development',
                             'folder': 'Kestral/Burtree Lane/Development',
                             'children': [{'name': 'Fee Proposals',
                                           'folder': 'Kestral/Burtree Lane/Development/Fee Proposals',
                                           'children': []}]}]}]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:13:18