2013-10-02 37 views
0

嘗試使用python的改變與在字典中鍵的值,當我把這個字典{「X」它沒有返回正確的輸出Python函數沒有返回正確的輸出

def fetchAndReplace(dictionary,key,newValue): 
    keys = dictionary.keys() 
    for i in keys: 
     if i == key: 
      print dictionary[key] 
      dictionary[key] = newValue 
      return 

     else: 
      return "Nothing" 

: 3,'y':2},其中x代表key,6代表newValue 它返回字符串nothing,它不應該。我找不到任何錯誤的代碼,所以如果你能指出我忽略的錯誤,我會很感激。

+3

你明白'for'的作用嗎? –

+1

一旦你在'for'循環中的第一個'i'返回Nothing'',循環和函數結束。 – mVChr

+4

'dictionary ['x'] = 6'有什麼問題? – dawg

回答

2

認爲你正在嘗試做的東西沿着這些路線:

def fetchAndReplace(dictionary,key,newValue): 
    if key in dictionary: 
     dictionary[key]=newValue 
     return dictionary 
    else: 
     return 'Nothing' 

di= {'x':3,'y':2} 

print fetchAndReplace(di, 'z', 6)  
print fetchAndReplace(di, 'x', 6) 

打印:

Nothing 
{'y': 2, 'x': 6} 
+0

這與我所尋找的更接近。呼籲擺脫for循環。我正在幫助一位朋友做他的功課,而且這已經過了漫長的一天,所以這只是因爲某種原因而忽略了我的頭腦。不過現在很明顯。謝謝。 – WhyAyala

3

問題是你在return在第一次迭代,所以你永遠不會到第二個關鍵。

試試這個:

def fetchAndReplace(dictionary, key,newValue): 
    keys = dictionary.keys() 
    for i in keys: 
     if i == key: 
      dictionary[key] = newValue 

    return dictionary 



print fetchAndReplace({'x':3,'y':2}, 'x', 6) 

輸出:

{'y': 2, 'x': 6} 

此外,您也能完成同樣的與dict.update方法的功能:

>>> mydict = {'x':3,'y':2} 
>>> mydict.update({'x': 6}) 
>>> print mydict 
{'y': 2, 'x': 6} 

H個,
亞倫

0

打印語句總是幫助

def fetchAndReplace(dictionary,key,newValue): 
    keys = dictionary.keys() 
    print 'keys:', keys 
    for i in keys: 
     print 'i:', i, 'i == key:', i == key 
     if i == key: 
      print dictionary[key] 
      dictionary[key] = newValue 
      return 

     else: 
      return "Nothing" 

項目在一本字典是幾乎任意訂購,如果條件語句if i == key失敗,鍵中的第一項,函數將返回

0

我很想回答這個問題。

您只需要刪除兩個製表符(或8個,如果您使用空格)以使您的代碼正常工作。

減少else:return "Nothing"

結果的縮進:

def fetchAndReplace(dictionary, key, newValue): 
    keys = dictionary.keys() 
    for i in keys: 
     if i == key: 
      print dictionary[key] 
      dictionary[key] = newValue 
      return 
    else: 
     return "Nothing" 

dictionary = {"x":1, "y":2} 
print "The result is: " + str(fetchAndReplace(dictionary,"x",3)) 
print "The result is: " + str(fetchAndReplace(dictionary,"z",0)) 

這將產生:

 
1 
The result is: None 
The result is: Nothing 

爲什麼?因爲通過減小壓痕,所述else會附着for,並且根據該documentation,所述else部分for..else將僅當for循環正常退出執行(即,不breakreturn),這就是爲什麼它將迭代在所有條目中,只有當找不到密鑰時,纔會返回字符串「Nothing」。否則它將返回None,因爲您只有語句return

但由於其他人已經注意到了,你可能會想是這樣的:

def fetchAndReplace(dictionary, key, newValue): 
    result = dictionary.get(key, "Nothing") 
    dictionary[key] = newValue 
    return result 

其邏輯是保存在變量resultdictionary[key]原始值,如果密鑰不可用,這將是分配值Nothing。然後,您將該密鑰的值替換爲dictionary[key] = newValue,然後返回result

運行此代碼:

dictionary = {"x":1, "y":2} 
print "The result is: " + fetchAndReplace(dictionary,"x",3) 
print "The result is: " + fetchAndReplace(dictionary,"z",0) 

會產生

 
The result is: 1 
The result is: Nothing 
0

好像你想在那裏不是一本字典情況來規劃。但是,您已經創建了一個。沒有任何回報。