Changing one dict changes all dicts in a list of dicts [duplicate]

情到浓时终转凉″ 提交于 2020-01-30 09:13:13

问题


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.

The obtained result of above program is

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]}]

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?


回答1:


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



来源:https://stackoverflow.com/questions/57990256/changing-one-dict-changes-all-dicts-in-a-list-of-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!