如何复制字典,只编辑副本 [英] How to copy a dictionary and only edit the copy

查看:88
本文介绍了如何复制字典,只编辑副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释一下吗?这对我来说没有任何意义。



我将字典复制到另一个字体,并编辑第二个字符,两者都被更改。为什么会发生这种情况?

 >>> dict1 = {key1:value1,key2:value2} 
>>> dict2 = dict1
>>> dict2
{'key2':'value2','key1':'value1'}
>>> dict2 [key2] =为什么?
>>> dict1
{'key2':'WHY ?!','key1':'value1'}


解决方案

Python 永不隐式复制对象。当您设置 dict2 = dict1 时,您将使它们引用相同的精确的dict对象,因此当您更改它时,对其进行的所有引用将保持引用当前的对象状态。



如果要复制dict(这是罕见的),您必须明确地使用

  dict2 = dict(dict1)

  dict2 = dict1.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'}

解决方案

Python never implicitly copies objects. 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.

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

dict2 = dict(dict1)

or

dict2 = dict1.copy()

这篇关于如何复制字典,只编辑副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆