Why does updating one dictionary object affect other?

前端 未结 1 1763
陌清茗
陌清茗 2020-12-02 00:54

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

相关标签:
1条回答
  • 2020-12-02 01:17
    >>> 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.

    0 讨论(0)
提交回复
热议问题