Why does updating one dictionary object affect other?

偶尔善良 提交于 2019-12-17 10:01:09

问题


I have a nested dictionary, let's call it dictionary d. The key of this dictionary is an integer, and the value of each key is another dictionary. I'm trying a simple code on python 2.7 to update the value of one outer key, but it seems that it's updating the values of ALL of the outer key.

Hope these codes will make it easier to understand. Here's my input.

>>> template = {'mean':0,'median':0}
>>> d[0] = template
>>> d[1] = template
>>> d[0]['mean'] = 1
>>> d

and then here's the output:

{0: {'mean':1, 'median':0}, 1:{'mean':1,'median':0}}

you see, I only assigned '1' to d[0]['mean'], but somehow the d[1]['mean'] is also updated. If i increase the number of keys in the d, it will just change ALL of the ['mean'] values on all d keys.

Am I doing anything wrong here? Is this a bug?


回答1:


>>> d[0] = template
>>> d[1] = template

These two statements made both d[0] and d[1] refer to the same object, template. Now you can access the dictionary with three names, template, d[0] and d[1]. So doing:

d[0]['mean'] = 1

modifies a dictionary object, which can be referred with the other names mentioned above.

To get this working as you expected, you can create a copy of the template object, like this

>>> d[0] = template.copy()
>>> d[1] = template.copy()

Now, d[0] and d[1] refer to two different dictionary objects.



来源:https://stackoverflow.com/questions/29116226/why-does-updating-one-dictionary-object-affect-other

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