将字典附加到列表-我看到一个类似指针的行为

我在 python 解释器中尝试了以下方法:

>>> a = []
>>> b = {1:'one'}
>>> a.append(b)
>>> a
[{1: 'one'}]
>>> b[1] = 'ONE'
>>> a
[{1: 'ONE'}]

在这里,在将字典 b追加到列表 a之后,我将更改字典 b中与键 1对应的值。不知何故,这种变化也反映在列表中。当我向列表追加字典时,我不仅仅是追加字典的值吗?看起来好像我已经在列表中追加了一个指向字典的指针,因此对字典的更改也反映在列表中。

我不希望更改反映在列表中。我如何做到这一点?

244773 次浏览

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

Also with dict

a = []
b = {1:'one'}


a.append(dict(b))
print a
b[1]='iuqsdgf'
print a

result

[{1: 'one'}]
[{1: 'one'}]