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

基于主键合并列表中的多个字典

嘿,这个需求其实挺常见的,我来给你几个实用的Python解法,完美解决你的字典合并问题:

解法一:基础循环实现(直观易懂)

这个方法逻辑清晰,适合所有阶段的Python开发者:

l = [{"primary_key": 5164, "attribute1": 2}, {"primary_key": 5162, "attribute1": 3}, {"primary_key": 5164, "attribute2": 3}]
temp_dict = {}

for item in l:
    pk = item["primary_key"]
    if pk not in temp_dict:
        # 首次遇到该primary_key,复制原字典存入临时容器
        temp_dict[pk] = item.copy()
    else:
        # 已存在的话,合并键值对(重复键会被后续值覆盖)
        temp_dict[pk].update(item)

# 将临时字典的取值转换为列表,得到最终结果
output_l = list(temp_dict.values())
print(output_l)
解法二:使用collections.defaultdict(更简洁)

如果你熟悉Python标准库,用defaultdict能让代码更紧凑:

from collections import defaultdict

l = [{"primary_key": 5164, "attribute1": 2}, {"primary_key": 5162, "attribute1": 3}, {"primary_key": 5164, "attribute2": 3}]
temp_dict = defaultdict(dict)

for item in l:
    pk = item["primary_key"]
    # 无需手动判断键是否存在,defaultdict会自动创建空字典
    temp_dict[pk].update(item)

output_l = list(temp_dict.values())
print(output_l)

补充说明

  • 两种方法的核心逻辑一致:用primary_key作为临时字典的键,将同主键的字典通过update方法合并
  • 如果同一个primary_key下出现重复属性(比如两个attribute1),后续的属性值会覆盖之前的,这符合常规的合并预期
  • 第一种方法里用item.copy()是为了避免修改原列表中的原始字典,如果你不需要保留原数据,也可以直接赋值temp_dict[pk] = item

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:42:49