2016-12-04 101 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']}