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

Python如何将父子关联字典列表转换为嵌套字典

问题原因

你之前的代码只完成了按父ID分组节点的步骤,没有将分组后的子节点挂载到对应父节点下,因此无法生成目标嵌套结构。

实现逻辑

整个转换流程非常直接:

  • 先构建ID到节点的映射,实现O(1)复杂度的节点查找,避免反复遍历列表
  • 复用你已写的分组逻辑,按parent_section_id聚合所有节点,得到每个父ID对应的直接子节点列表
  • 遍历所有节点,将对应分组的子节点列表赋值到节点的child字段
  • 提取根节点(parent_section_id值为None的节点),即为最终的嵌套结构
参考代码
# 原始输入数据
test = [
        {"id": "101", "logical_section": "ORGANIZATION", "parent_section_id": None},
        {"id": "102", "logical_section": "ORG_NAMES", "parent_section_id": "101"},
        {"id": "103", "logical_section": "ORG_ADDRESSES", "parent_section_id": "101"},
        {"id": "104", "logical_section": "SOURCEADDRESS", "parent_section_id": "103"},
        {"id": "105", "logical_section": "STANDARDIZEDADDRESS", "parent_section_id": "103"},
        {"id": "106", "logical_section": "ORG_EMPLOYES", "parent_section_id": "101"}
]

# 构建ID-节点快速索引
node_map = {item["id"]: item for item in test}
# 按父ID分组子节点
parent_child_map = {}
for node in test:
    parent_child_map.setdefault(node["parent_section_id"], []).append(node)
# 为每个节点挂载子节点
for node in test:
    if node["id"] in parent_child_map:
        node["child"] = parent_child_map[node["id"]]
# 提取根节点(单根场景直接取第一个元素即可)
root = [n for n in test if n["parent_section_id"] is None][0]

代码运行后root的结构和你给出的预期输出完全匹配。如果业务场景存在多个根节点,最后一步不需要取[0],直接保留列表形式的结果即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:36:37