我设置了dict2 = dict1。当我编辑dict2时,原来的dict1也改变了。为什么?

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

当前回答

当你赋值dict2 = dict1时,你并没有创建一个dict1的副本,结果是dict2只是dict1的另一个名字。

要复制像字典这样的可变类型,使用copy模块的copy / deepcopy。

import copy

dict2 = copy.deepcopy(dict1)

其他回答

在python 3.5+上,有一种更简单的方法来实现浅拷贝,即使用** unpackaging操作符。由Pep 448定义。

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

**将字典解包到一个新字典中,然后分配给dict2。

我们还可以确认每个字典都有一个不同的id。

>>>id(dict1)
 178192816

>>>id(dict2)
 178192600

如果需要深度复制,那么copy.deepcopy()仍然是可行的方法。

下面的代码是在dicts上的,它遵循json语法,比deepcopy快3倍以上

def CopyDict(dSrc):
    try:
        return json.loads(json.dumps(dSrc))
    except Exception as e:
        Logger.warning("Can't copy dict the preferred way:"+str(dSrc))
        return deepcopy(dSrc)
>>> 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)

如果你的字典是映射类型,你不能.copy()它,但你可以

dict2 = dict1 | {}

它有点模糊,与copy.copy(dict1)相比,我不能说它的性能如何,但它非常简洁。

使用for循环进行复制:

orig = {"X2": 674.5, "X3": 245.0}

copy = {}
for key in orig:
    copy[key] = orig[key]

print(orig) # {'X2': 674.5, 'X3': 245.0}
print(copy) # {'X2': 674.5, 'X3': 245.0}
copy["X2"] = 808
print(orig) # {'X2': 674.5, 'X3': 245.0}
print(copy) # {'X2': 808, 'X3': 245.0}