尝试在python中创建字典列表时出现意外列表 [英] Unexpected list when trying to create a list of dictionaries in python
问题描述
我正在尝试创建字典列表.预期的结果是,对于5个学生,它在列表中应该有5个字典项,键是名称"和标记"(在列表中).我得到的输出是为迭代中的最后一个学生重复5次信息.请让我知道我在哪里出错.
I am trying to create a list of dictionary. The expected output is that for 5 Students, it should have 5 dictionary items in the list with keys being Name and Marks (in a list). The output that I get is having the information repeated 5 times for the last student in iteration. Please let me know where am I making an error.
import random
name_list=[]
name_list = ['A','B','C','D','E']
stud_dict=dict()
stud_dict_list = []
for name in name_list:
mark_list = []
for i in range(1,11):
mark_list.append(random.randint(0,100))
stud_dict['Name']=name
stud_dict['Marks']=mark_list
stud_dict_list.append(stud_dict)
print(stud_dict_list)
output:
[{'Name': 'E', 'Marks': [91, 71, 93, 33, 52, 90, 97, 98, 41, 18]}, {'Name': 'E', 'Marks': [91, 71, 93, 33, 52, 90, 97, 98, 41, 18]}, {'Name': 'E', 'Marks': [91, 71, 93, 33, 52, 90, 97, 98, 41, 18]}, {'Name': 'E', 'Marks': [91, 71, 93, 33, 52, 90, 97, 98, 41, 18]}, {'Name': 'E', 'Marks': [91, 71, 93, 33, 52, 90, 97, 98, 41, 18]}]
推荐答案
已经问过很多遍了,但是我没有时间搜索确切的dup ATM,所以:
This has been asked many times but I don't have time to search for an exact dup ATM, so:
Python 从不复制内容.在这里,您将相同字典一遍又一遍地添加到列表中:
Python never copies things unless explicitely asked for. Here, you're adding the same dict to your list over and over again:
>>> import random
>>> name_list=[]
>>> name_list = ['A','B','C','D','E']
>>> stud_dict=dict()
>>> stud_dict_list = []
>>> for name in name_list:
... mark_list = []
... for i in range(1,11):
... mark_list.append(random.randint(0,100))
... stud_dict['Name']=name
... stud_dict['Marks']=mark_list
... stud_dict_list.append(stud_dict)
...
>>> stud_dict
{'Name': 'E', 'Marks': [94, 51, 79, 82, 84, 76, 92, 96, 7, 52]}
>>> id(stud_dict)
139663685096344
>>> [id(item) for item in stud_dict_list]
[139663685096344, 139663685096344, 139663685096344, 139663685096344, 139663685096344]
>>>
由于它是完全相同的字典,因此该字典的每次更新当然都会反映在列表中.解决方案非常简单,每次都创建一个新字典:
Since it's the very same dict, each update of the dict will of course be reflected in the list. And the solution is quite simply to create a new dict each time:
import random
name_list = ['A','B','C','D','E']
stud_dict_list = []
for name in name_list:
mark_list = []
for i in range(1,11):
mark_list.append(random.randint(0,100))
stud_dict = {'Name': name, 'Marks': mark_list}
stud_dict_list.append(stud_dict)
您还希望阅读此内容,以获取有关Python变量的更多信息 ...
这篇关于尝试在python中创建字典列表时出现意外列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!