如果一次又一次地使用同一个字典,Python字典数据不会得到更新

2024-05-15 08:54:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着创建一个包含一套字典的字典。为此,我写了下面。 但由于python中的一切都是对象,即使我已将新学员分配给dictionary student, 当我打印数据时,我只能看到123个数据。需要详细了解此行为以及如何克服此问题

students = {}

student = {}
student['id'] = 123
student['first_name'] = 'Raj'
student['last_name'] = 'Nath'

students[123] = student

student['id'] = 124
student['first_name'] = 'Naveen'
student_1['last_name'] = 'Jain'

students[124] = student

print(students)

Tags: 数据对象nameiddictionary字典studentfirst
3条回答

students[123] = student中,学生词典存储在123键下。但它不是复制的。仍然在student变量下,存在您正在访问的同一目录:

student['id'] = 124
student['first_name'] = 'Naveen'
student_1['last_name'] = 'Jain'

因为它仍然是同一个字典,所以您将用新值覆盖旧值

如果要复制字典,请使用:

students[123] = student.copy()

但更准确的方法是在分配以下内容后创建新的空字典:

students[123] = student
student = {}

Python几乎总是通过引用传递,以减少内存上的操作数。你可以阅读更多关于它的内容

您的方法多次将相同的student字典存储到students字典中。所有不同的实例students[0], ..., students[n]实际上都指向同一个对象,该对象包含上次提交的更新中指定的值

为了使事情顺利进行,您必须在每次为新学生输入数据时实例化一个新词典,我发现使用类构造函数代替通常的文本尤其方便,但可能只是我

students = {}
students[123] = dict(id=123, first_name='Raj', last_name='Nath')
students[124] = dict(id=124, first_name='Naveen', last_name='Jain')

此外,遵循最少重复的原则,可以

students = {}
students[123] = dict(first_name='Raj', last_name='Nath')
students[124] = dict(first_name='Naveen', last_name='Jain')

ps1:当然,最大复制也是一个相互竞争的原则,你应该选择你喜欢的;-)


ps2:id是一个Python内置函数,您可以为id分配一个整数,Python是自由的,但是您的程序的其他部分现在有被神秘破坏的危险…

这里的问题是您没有创建新词典。运行行students[123] = student时,传递了存储在变量student中的字典。之后,您继续修改同一本词典。我建议创建字典(students[123] = student.copy())的副本并将其存储在students中,或者为每个学生创建一个新字典

使用副本:

students = {}

student = {}
student['id'] = 123
student['first_name'] = 'Raj'
student['last_name'] = 'Nath'

students[123] = student.copy() # This stores a copy of the dictionary

student['id'] = 124
student['first_name'] = 'Naveen'
student['last_name'] = 'Jain'

students[124] = student

print(students)

使用新词典:

students = {}

student = {}
student['id'] = 123
student['first_name'] = 'Raj'
student['last_name'] = 'Nath'

students[123] = student

student = {} # Create a new dictionary to be used for the new student
student['id'] = 124
student['first_name'] = 'Naveen'
student['last_name'] = 'Jain'

students[124] = student

print(students)

相关问题 更多 >