Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - 如何复制字典并仅编辑副本(How to copy a dictionary and only edit the copy)

Can someone please explain this to me?

(有人可以向我解释一下吗?)

This doesn't make any sense to me.

(这对我来说毫无意义。)

I copy a dictionary into another and edit the second and both are changed.

(我将字典复制到另一个字典中,然后编辑第二个字典,并且两者都已更改。)

Why is this happening?

(为什么会这样呢?)

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'value2', 'key1': 'value1'}
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
  ask by MadSc13ntist translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Python never implicitly copies objects.

(Python 绝不会隐式复制对象。)

When you set dict2 = dict1 , you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.

(设置dict2 = dict1dict2 = dict1它们引用相同的确切dict对象,因此,在对它进行突变时,对其的所有引用将始终引用该对象的当前状态。)

If you want to copy the dict (which is rare), you have to do so explicitly with

(如果要复制字典(这种情况很少见),则必须使用)

dict2 = dict(dict1)

or

(要么)

dict2 = dict1.copy()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...