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

Python中列表字典项合并至字典时重复添加最后一项的问题

问题原因与解决方案

嘿,这是Python里字典引用的经典陷阱,我帮你捋清楚!

问题根源

你在循环里写了aux_dict = dictionary,但这并没有创建一个新的字典——它只是让aux_dict变量指向了原dictionary的内存地址。也就是说,循环中每次修改aux_dict["extra"],其实都是在修改同一个原字典,最后你把同一个字典的引用重复添加到了res列表里,所以最终所有元素都显示最后一次的修改结果。

解决方法

我们需要每次循环都创建原字典的副本,而不是直接引用。这里有几种简单的实现方式:

方法1:使用dict()构造函数创建副本

res = []
dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
    {"surname": "Doe", "email": "jd@example.com"},
    {"surname": "Morrison", "email": "jm@example.com"},
    {"surname": "Targetson", "email": "jt@example.com"}
]

for info in dictionary_2:
    aux_dict = dict(dictionary)  # 创建原字典的浅拷贝
    aux_dict["extra"] = info
    res.append(aux_dict)

print(res)

方法2:使用字典的copy()方法

res = []
dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
    {"surname": "Doe", "email": "jd@example.com"},
    {"surname": "Morrison", "email": "jm@example.com"},
    {"surname": "Targetson", "email": "jt@example.com"}
]

for info in dictionary_2:
    aux_dict = dictionary.copy()  # 同样是浅拷贝
    aux_dict["extra"] = info
    res.append(aux_dict)

print(res)

方法3:用字典解包语法(更简洁)

甚至可以不用中间变量,直接在列表推导式里构造新字典:

dictionary = {"id": 1, "name": "Jhon"}
dictionary_2 = [
    {"surname": "Doe", "email": "jd@example.com"},
    {"surname": "Morrison", "email": "jm@example.com"},
    {"surname": "Targetson", "email": "jt@example.com"}
]

res = [{**dictionary, "extra": info} for info in dictionary_2]
print(res)

补充说明

这里用的都是浅拷贝,因为你的原字典里的values都是不可变类型(int和str),完全够用。如果原字典里包含可变对象(比如列表、嵌套字典),那你可能需要用copy.deepcopy()来创建深度拷贝,但这个场景里不需要~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:10:22