我设置了dict2 = dict1。当我编辑dict2时,原来的dict1也改变了。为什么?
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
我设置了dict2 = dict1。当我编辑dict2时,原来的dict1也改变了。为什么?
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
当前回答
Python从不隐式复制对象。当您设置dict2 = dict1时,您将使它们引用相同的dict对象,因此当您更改它时,对它的所有引用都将引用处于当前状态的对象。
如果您想复制字典(这是罕见的),您必须显式地使用
dict2 = dict(dict1)
or
dict2 = dict1.copy()
其他回答
Dict2 = dict1不复制字典。它只是为程序员提供了另一种方法(dict2)来引用同一个字典。
Dict1是一个引用底层字典对象的符号。将dict1赋值给dict2只是赋值相同的引用。通过dict2符号更改键的值将更改底层对象,这也会影响dict1。这很令人困惑。
推断不可变值比推断引用要容易得多,所以尽可能地复制:
person = {'name': 'Mary', 'age': 25}
one_year_later = {**person, 'age': 26} # does not mutate person dict
这在语法上是相同的:
one_year_later = dict(person, age=26)
你可以直接使用:
dict2 = eval(repr(dict1))
其中对象dict2是dict1的独立副本,因此可以修改dict2而不影响dict1。
这适用于任何类型的对象。
>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1
复制Dict对象有很多方法,我简单用一下
dict_1 = {
'a':1,
'b':2
}
dict_2 = {}
dict_2.update(dict_1)
对于嵌套的字典,不要使用dict(srcData)或srcData.copy()或{**srcData},因为如果你改变了秒级或更多,它也会修改源字典
srcData = {
'first': {
'second': 'second Value'
}
}
newData = dict(srcData) # srcData.copy() or {**srcData}
newData['first']['second'] = 'new Second Value'
print(srcData)
print(newData)
# it will print
# srcData: {'first': {'second': 'new Second Value'}}
# newData:{'first': {'second': 'new Second Value'}}
# but it should be
# srcData: {'first': {'second': 'second Value'}}
# newData:{'first': {'second': 'new Second Value'}}
deepcopy的另一个选择是使用json技巧,如Javascript json .parse(json .stringify(obj))
import json
srcData = {'first': {'second': 'second Value'}}
newData = json.loads(json.dumps(srcData))
newData['first']['second'] = 'new Second Value'
print(srcData)
print(newData)
# srcData: {'first': {'second': 'second Value'}}
# newData: {'first': {'second': 'new Second Value'}}