更改一个字典将更改字典列表中的所有字典 [英] Changing one dict changes all dicts in a list of dicts

查看:61
本文介绍了更改一个字典将更改字典列表中的所有字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于存储数据的字典列表.当我对一个命令进行更改时,该更改将反映在所有命令中.

I have a list of dicts for storing data. When I make change in one dict, that change is reflected in all dicts.

students = [{"marks": [], "subjects": 0}]*3
specific_student = 2
print("Before updating", students)
students[specific_student]["marks"].append(50)
students[specific_student]["subjects"] += 1
print("After updating", students)

我期望只有最后一个字典会被更新.但令人惊讶的是,所有命令都被更改了.

I was expecting that, only last dict will get updated. but surprisingly all dicts were changed.

上述程序的获得的结果

Before editing [{'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}]
After editing [{'subjects': 1, 'marks': [50]}, {'subjects': 1, 'marks': [50]}, {'subjects': 1, 'marks': [50]}]

但是预期结果(仅更改了位置2的字典)

But the expected result(only dict at position 2 gets changed) was

Before editing [{'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}]
After editing [{'subjects': 0, 'marks': []}, {'subjects': 0, 'marks': []}, {'subjects': 1, 'marks': [50]}]

有人可以解释这种奇怪的行为并提出解决方案以获得预期结果吗?

Can some one explain this strange behavior and suggest a solution to obtain the expected result?

推荐答案

您需要在列表上使用.copy(),否则它将是您的字典的链接,而不是具有相同值的新字典.>请注意,您需要在每个字典和列表上都使用.copy(),甚至要复制在字典/列表中的那些

You need to use .copy() onto your list, else it would be a link of your dict and not a new dict with the same values.
Note that you need to use .copy() on EVERY dict and list you want to copy, even those in your dict/list

这篇关于更改一个字典将更改字典列表中的所有字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆