python字典可变澄清

python字典可变澄清,python,dictionary,mutable,Python,Dictionary,Mutable,我使用dictionary作为函数的参数 当我更改传递的参数的值时,它将被更改为父字典。我使用了dict.copy(),但仍然无效 如何避免字典中的可变值。需要你的投入吗 >>> myDict = {'one': ['1', '2', '3']} >>> def dictionary(dict1): dict2 = dict1.copy() dict2['one'][0] = 'one' print dict2 >>&g

我使用dictionary作为函数的参数

当我更改传递的参数的值时,它将被更改为父字典。我使用了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']}

我的意图是我父母的字典应该被修改。 谢谢 Vignesh使用
copy
模块中的
deepcopy()

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


您可以使用
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']}

“我的意图是我的父母字典应该被修改。”这就是正在发生的事情。你的意思是说你的意图是不应该改变吗?
dict2 {'one': ['one', '2', '3']}
myDict {'one': ['1', '2', '3']}