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

Python循环向list追加dictionary时所有条目均与最后一次输入相同如何解决

问题原因
  • Python 中的字典属于可变对象,你将dictionary定义在循环外,全程只会创建一个字典实例,所有对键的修改都是作用在同一个内存地址的对象上
  • list.append(dictionary) 操作实际是将这个字典的引用添加到列表中,并不是拷贝一份新的字典存入列表,因此列表中所有元素本质都指向同一个字典,最后一次修改会覆盖之前的所有值
  • 额外提示:你使用了内置类型名list作为变量名,会覆盖Python自带的list()构造方法,属于不规范的命名方式,建议更换为student_list这类自定义名称
解决方案

方案1:每次循环创建新字典

直接把字典定义放到循环内部,每次循环生成全新的字典实例:

a = 2
student_list = []
for i in range(a):
    # 每次循环都创建新的字典
    dictionary = {
        "student_name": "",
        "Age": "",
        "email": ""
    }
    dictionary["student_name"] = input("enter student name: ")
    dictionary["Age"] = input("enter student age: ")
    dictionary["email"] = (dictionary["student_name"].replace(" ", "") + dictionary["Age"] + "@mycampus.com").lower()
    student_list.append(dictionary)

print(student_list)

方案2:添加到列表时拷贝字典

如果需要保留外部的字典模板,可以在append时对字典做浅拷贝:

a = 2
student_list = []
dictionary_template = {
    "student_name": "",
    "Age": "",
    "email": ""
}
for i in range(a):
    # 基于模板生成新的字典副本
    dictionary = dictionary_template.copy()
    dictionary["student_name"] = input("enter student name: ")
    dictionary["Age"] = input("enter student age: ")
    dictionary["email"] = (dictionary["student_name"].replace(" ", "") + dictionary["Age"] + "@mycampus.com").lower()
    student_list.append(dictionary)

print(student_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:27:04