Why does updating one dictionary object affect oth

2019-01-20 03:25发布

问题:

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.