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

Python如何基于唯一id安全合并嵌套字典列表中的重复项

合并字典列表重复项方案

实现思路

  • 以字典元素的id字段为唯一键,构建临时映射字典存储聚合后的数据
  • 遍历原始列表的每个元素:
    • 若当前元素的id不在映射字典中,直接将元素存入映射字典
    • 若id已存在,将当前元素的interfaces列表追加到对应id的interfaces列表中
  • 最后将映射字典的值转换为列表,即可得到合并后的结果

代码实现

# 原始输入数据
input_list = [
    {'id': 2404, 'interfaces': [{'port': 78, 'module': 1 }]},
    {'id': 2404, 'interfaces': [{'port': 79, 'module': 1 }]},
    {'id': 1234, 'interfaces': [{'port': 79, 'module': 1 }]}
]

# 按id聚合的临时映射
id_agg_map = {}
for item in input_list:
    item_id = item['id']
    if item_id not in id_agg_map:
        # 新id直接存入,用copy避免修改原数据
        id_agg_map[item_id] = item.copy()
    else:
        # 已有id合并interfaces列表
        id_agg_map[item_id]['interfaces'].extend(item['interfaces'])

# 转换为目标列表格式
result = list(id_agg_map.values())
print(result)

扩展说明

如果需要对interfaces内部的重复端口配置也做去重处理,可以追加以下逻辑:

for item in result:
    # 利用字典键唯一性去重,保留首个出现的配置
    unique_inf = list({(inf['port'], inf['module']): inf for inf in item['interfaces']}.values())
    item['interfaces'] = unique_inf

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:15:04