python 字典可变说明

python Dictionary Mutable Clarification

我正在使用字典作为函数的参数。

当我更改传递的参数的值时,它会更改父 dictionary.i 使用了 dict.copy() 但仍然无效。

如何避免字典值可变。需要您的意见

>>> myDict = {'one': ['1', '2', '3']}
>>> def dictionary(dict1):
    dict2 = dict1.copy()
    dict2['one'][0] = 'one'
    print dict2


>>> dictionary(myDict)
{'one': ['one', '2', '3']}
>>> myDict
{'one': ['one', '2', '3']}

我的本意是应该更改我的父词典。 谢谢, 维涅什

使用 copy 模块中的 deepcopy()

from copy import deepcopy
myDict = {'one': ['1', '2', '3']}
def dictionary(dict1):
    dict2 = deepcopy(dict1)
    dict2['one'][0] = 'one'
    print dict2

参见the docs

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.

您可以使用 copy 模块中的 deepcopy,如下例所示:

from copy import deepcopy

myDict = {'one': ['1', '2', '3']}

def dictionary(dict1):
    dict2 = deepcopy(dict1)
    dict2['one'][0] = 'one'
    print  dict2

dictionary(myDict)
print(myDict)

输出:

dict2 {'one': ['one', '2', '3']}
myDict {'one': ['1', '2', '3']}