首页 > 解决方案 > 列表中的字典条目变得相同

问题描述

我想存储数据

list = [
    {
        "student_name": "",
        "Age": "",
        "email": ""
    },
    {
        "student_name": "",
        "Age": "",
        "email": ""
    },
]

字典存储在一个名为字典的变量中,但出现错误,每个索引中的字典数据都更新为最后输入的数据

这是错误 在此处输入图像描述

代码:

a = 2
list = []
dictionary = {
    "student_name": "",
    "Age": "",
    "email": ""
}
for i in range(a):
    dictionary["student_name"] = input("enter student name: ")
    dictionary["Age"] = input("enter student age: ")
    dictionary["email"] = (dictionary["student_name"].replace(" ", "") + dictionary["Age"] + "@mycampus.com").lower()
    list.append(dictionary)

print(list)

标签: pythonlistdictionary

解决方案


您正在附加相同的条目。所以首先,第二个条目都指向同一个字典。所以无论字典的值是什么,这将是两个条目。您可以将其视为指向同一个对象。

for i in range(a):
    dictionary = dict()
    dictionary["student_name"] = input("enter student name: ")
    dictionary["Age"] = input("enter student age: ")
    dictionary["email"] = (dictionary["student_name"].replace(" ", "") + dictionary["Age"] + "@mycampus.com").lower()
    list.append(dictionary)

print(list)

推荐阅读