2016-12-04 8 views
0

私は関数の引数として辞書を使用しています。pythonの辞書変更可能な明確化

私は渡された引数の値を変更するとき、それは変更取得親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']} 

私の意図は親辞書を変更する必要がありました。 ありがとう、 Vignesh

+0

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

+0

「私の意図は、私の親の辞書を変更する必要がありました。」それが起こっていることです。あなたの意図は、それは* *変更してはならないということであると言うことを意味していましたか? – BrenBarn

答えて

1

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を参照してください:

あなたはこの例のように copyモジュールから deepcopyを使用することができます
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

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']} 
関連する問題