2016-12-04 71 views
0

我使用字典作为参数的函数。python字典可变澄清

当我改变通过参数的值,它得到改变父字典。我已经使用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

+0

http://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy – Jakub

+0

“我的意图是我的父母字典应该改变。”这就是发生的事情。你的意思是说你的意图是不应该改变? – BrenBarn

回答

1

使用deepcopy()copy模块。

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. 
0

您可以使用deepcopycopy模块这样的例子:

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']}