2012-11-26 43 views
2

Python新手的位,但是可以執行以下操作嗎?在Python中的字典中保持相同的值

>>>random_dict=dict(a=2) 
>>>addOnlyOneValue(random_dict) 
{'a': 3} 
>>>addOnlyOneValue(random_dict) 
{'a': 3} 

我所做的:

def addOnlyOneValue(random_dict): 
    random_dict2=random_dict  #I thought random_dict and random_dict2 would be modified independently  
    for val in random_dict2.keys(): 
     random_dict2[val]+=1 
    print (random_dict2) 

但是,如果我這樣做,我得到如下:

>>>random_dict=dict(a=2) 
>>>addOnlyOneValue(random_dict) 
{'a': 3} 
>>>addOnlyOneValue(random_dict) 
{'a': 4} 

是否有可能以某種方式重新random_dict其原始值(這裏random_dict = dict(a = 2))在addOnlyOneValue函數中?

回答

3

你想要做什麼是copy()字典:

random_dict2 = random_dict.copy() 

在你的榜樣,你只是做random_dict2random_dict參考 - 你想要的是創造一個新的,具有相同的值(注意這是一個淺拷貝,所以如果你的字典有可變項目,新字典將指向那些項目,這可能會導致看起來很奇怪的行爲)。

注意,而不是手動循環,你可以用dictionary comprehension做到這一點:

def addOnlyOneValue(random_dict): 
    print({key: value+1 for key, value in random_dict.items()}) 

字典內涵是從現有的數據結構修改值以創建新字典的最佳方式。

1

將字典(或任何其他對象,除了字符串或數字)賦值給另一個賦值給該對象的引用的變量結果,它不會創建副本。你可以這樣做:

random_dict2 = dict(random_dict) 

類似的列表:

my_copy = list(some_list) 

需要注意的是這個副本是「淺」,這意味着,只列出被複制,並且將包含在包含對象的引用沒有副本對象。詳細瞭解copying in python

相關問題