python - 列表中的字典条目变得相同
问题描述
我想存储数据
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)
解决方案
您正在附加相同的条目。所以首先,第二个条目都指向同一个字典。所以无论字典的值是什么,这将是两个条目。您可以将其视为指向同一个对象。
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)
推荐阅读
- r - 如何删除不重复的数据?
- node.js - Squalise:TypeError:没有'new'(打字稿)就不能调用类构造函数模态
- javascript - 获取对象内对象数组的长度
- python - 如何从我制作的要存储在主程序中的全局变量中的函数中获取字符串?
- javascript - 如何在 Opencart 3.0 中按 sku 或按型号将产品添加到购物车
- python - 从系统某处调用脚本时如何导入配置文件?
- javascript - 将状态作为道具传递给 react-native-tab-view 的问题?
- excel - 将多个值从一个 .xlsm 文件返回到另一个
- javascript - 构建自定义threejs几何
- microsoft-graph-api - 访问 Graph API 以获取授权类型为 client_credentials 的特定用户的邮箱消息时出现“UnknownError”。仅限应用权限