You need to enable JavaScript to run this app. Python中如何对嵌套字典的已存在键追加并聚合对应值
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何对嵌套字典的已存在键追加并聚合对应值

多层嵌套字典同路径值聚合实现方案

现有实现的问题定位

你目前写的聚合逻辑仅在字典根层级完成键匹配,没有遍历嵌套结构的内部层级,相当于把每个同根键下的整个子字典作为黑盒存入列表,自然无法归集内层相同键路径对应的叶子值,最终结果和预期存在偏差。

核心实现思路

要完成深层嵌套的聚合,需要拆成三步处理:

  • 递归遍历每个原始字典,提取所有从根节点到叶子节点的完整键路径
  • 按照完整路径做分组,将同路径下的所有叶子值归集为列表
  • 将归集好的键值对重新还原为嵌套字典结构,按需调整输出格式适配不同需求

可直接运行的实现代码

from collections import defaultdict

def extract_full_paths(nested_dict, current_path=None, path_value_store=None):
    """递归遍历嵌套字典,提取完整键路径和对应叶子值"""
    # 初始化默认参数
    if current_path is None:
        current_path = []
    if path_value_store is None:
        path_value_store = defaultdict(list)
    
    for key, value in nested_dict.items():
        # 遇到嵌套字典则继续递归下探
        if isinstance(value, dict):
            extract_full_paths(value, current_path + [key], path_value_store)
        # 遇到叶子节点则记录完整路径和值
        else:
            full_path = tuple(current_path + [key])
            path_value_store[full_path].append(value)
    return path_value_store


def rebuild_nested_structure(path_value_store):
    """将路径-值映射重新拼接为多层嵌套字典"""
    root = {}
    for path, value_list in path_value_store.items():
        current_level = root
        # 逐层构建中间嵌套节点
        for node_key in path[:-1]:
            current_level = current_level.setdefault(node_key, {})
        # 最后一层节点存入归集好的值列表
        current_level[path[-1]] = value_list
    return root

效果验证

用你给出的原始列表做测试:

original_list = [
    {'animal': {'mammal': {'herbivore': 'zebra'}}},
    {'animal': {'mammal': {'herbivore': 'deer'}}},
    {'animal': {'mammal': {'carnivore': 'tiger'}}},
    {'animal': {'mammal': {'herbivore': 'lion'}}},
    {'furniture': {'chair'}}
]

# 全局归集所有路径的值
global_path_map = defaultdict(list)
for item in original_list:
    item_path_map = extract_full_paths(item)
    for path, values in item_path_map.items():
        global_path_map[path].extend(values)

# 还原为嵌套结构
aggregated_result = rebuild_nested_structure(global_path_map)

执行后得到的紧凑聚合结果为:

{
    'animal': {
        'mammal': {
            'herbivore': ['zebra', 'deer', 'lion'],
            'carnivore': ['tiger']
        }
    },
    'furniture': ['chair']
}

如果需要输出逐路径拆分的列表形式(也就是你举例的第三种聚合结果),只要增加一步拆分逻辑即可:

split_result = []
for path, values in global_path_map.items():
    # 从叶子层开始反向拼接嵌套结构
    single_node = {path[-1]: values}
    for node_key in reversed(path[:-1]):
        single_node = {node_key: single_node}
    split_result.append(single_node)

拆分后得到的列表结构为:

[
    {'animal': {'mammal': {'herbivore': ['zebra', 'deer', 'lion']}}},
    {'animal': {'mammal': {'carnivore': ['tiger']}}},
    {'furniture': ['chair']}
]

注:你举例提到的紧凑聚合结构存在Python语法偏差——同级嵌套的键不能拆成独立字典对象作为值,实际落地时将同层级的键合并写入同一个字典对象,就能生成完全合法的结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 06:36:06