Why does updating one dictionary object affect other?

>>> 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.

Leave a Comment