如何复制词典并仅编辑副本

2024-04-16 06:38:56 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能给我解释一下吗?这对我来说毫无意义

我把一本词典复制到另一本词典,然后编辑第二本词典,这两本词典都被修改了。为什么会这样

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

Tags: 编辑词典key2key1value1value2whydict1
3条回答

当您分配dict2 = dict1时,您不是在制作dict1的副本,它导致dict2只是dict1的另一个名称

要复制字典之类的可变类型,请使用^{}模块的copy/deepcopy

import copy

dict2 = copy.deepcopy(dict1)

Python从不隐式复制对象。当您设置dict2 = dict1时,您使它们引用相同的dict对象,因此当您对它进行变异时,对它的所有引用都会继续引用处于当前状态的对象

如果您想复制dict(这种情况很少见),那么必须使用

dict2 = dict(dict1)

dict2 = dict1.copy()

dict.copy()dict(dict1)生成副本时,它们只是副本。如果您想要深度副本,则需要copy.deepcopy(dict1)。例如:

>>> source = {'a': 1, 'b': {'m': 4, 'n': 5, 'o': 6}, 'c': 3}
>>> copy1 = x.copy()
>>> copy2 = dict(x)
>>> import copy
>>> copy3 = copy.deepcopy(x)
>>> source['a'] = 10  # a change to first-level properties won't affect copies
>>> source
{'a': 10, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> copy3
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}
>>> source['b']['m'] = 40  # a change to deep properties WILL affect shallow copies 'b.m' property
>>> source
{'a': 10, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy1
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy2
{'a': 1, 'c': 3, 'b': {'m': 40, 'o': 6, 'n': 5}}
>>> copy3  # Deep copy's 'b.m' property is unaffected
{'a': 1, 'c': 3, 'b': {'m': 4, 'o': 6, 'n': 5}}

关于浅拷贝与深拷贝,来自Python ^{} module docs

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

相关问题 更多 >