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

Python循环中嵌套字典值未正常更新的原因及解决方法

问题原因

Python字典的copy()方法是浅拷贝——它只会复制外层字典的键值对,但对于嵌套的子字典(比如这里的numbers),不会创建新的字典对象,只是把原字典里子字典的引用复制过去。

也就是说,循环里每次生成的new_dict,它们的numbers字段都指向同一个内存里的字典。每次修改new_dict["numbers"]["age"],都是在修改同一个子字典的值。循环结束时age最后一次赋值是40,所以所有people里的字典,numbers.age都会显示40。

如果age是外层键,浅拷贝会直接复制这个键值对到新字典,每个new_dict的age都是独立的,所以能得到30到40的不同值。

正确写法

方法1:使用深拷贝

导入copy模块,用deepcopy完全复制所有层级的字典:

import copy

template = {"first": "John", "last": "Doe", "numbers": {"age": 30}}
people = []
for age in range(30, 41):
    new_dict = copy.deepcopy(template)
    new_dict["numbers"]["age"] = age
    people.append(new_dict)

方法2:手动重建嵌套字典

每次循环时,重新创建numbers字典,避免引用同一个对象:

template = {"first": "John", "last": "Doe", "numbers": {"age": 30}}
people = []
for age in range(30, 41):
    new_dict = template.copy()
    # 重新生成numbers字典,替换原引用
    new_dict["numbers"] = {"age": age}
    people.append(new_dict)

方法3:直接构造新字典

跳过模板拷贝,每次循环直接生成完整的新字典:

people = []
for age in range(30, 41):
    new_dict = {
        "first": "John",
        "last": "Doe",
        "numbers": {"age": age}
    }
    people.append(new_dict)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:33:21