2013-07-19 37 views
0

所以我有這些值的字典:搜索字典功能想出什麼

{'AFG': (13, 0, 0, 2), 'ALG': (15, 5, 2, 8), 'ARG': (40, 18, 24, 28)} 

並假設用戶想要找出元組是做什麼用的三個字母的術語。那麼,他或她會說,'AFG',它會輸出。 [AFG,(13,0,0,2)]

但是,它提出了找不到匹配的代碼。

這是怎麼回事?我的名字和字典裏的名字一模一樣,沒有空格或者其他空白字符。

我的代碼:

def findMedals(countryDict, medalDict): 
    answer = [['Code','country','Gold','Silver','Bronze']] 

    search_str = input('What is the country you want information on? ') 

    #this block of code gets the country's name and three letter code onto the list 
    for code, country in countryDict.items(): 
     if code == search_str: 
      #This block should be getting executed if I type in, say, AFG 
      answer = [['country','code'], [country,code]] 
      print (answer) 
     else: 
      #but this is being ran instead 
      answer = [['country','code'], ['INVALID CODE', 'n/a']] 
      #return answer 


    print (medalDict) #debug code 
    #this block goes and appends the medal count to the list 
    for code, medalCount in medalDict.items(): 
     if search_str in code: 
     #this block should be getting executed 

      answer.append([medalCount]) 
     else: 
      #it will still put in the AFG's medal count, but with no match founds. 
      answer.append(['No Match Found']) 
    print (answer) #debug code 

我認爲它可能有一些做的else語句for循環,而是把它圈外似乎並沒有幫助的。

+1

爲什麼不只是'countryDict.get(search_str)'而不是循環? –

回答

0

您正在循環播放全部字典中的鍵和值。這意味着else塊將被要求在這循環,做匹配所有的鍵:

for code, country in countryDict.items(): 
    if code == search_str: 
     #This block should be getting executed if I type in, say, AFG 
     answer = [['country','code'], [country,code]] 
     print (answer) 
    else: 
     #but this is being ran instead 
     answer = [['country','code'], ['INVALID CODE', 'n/a']] 
     #return answer 

如果第一鍵值對掛繞不匹配,else塊執行,你似乎正在返回。

爲了尋找在字典中匹配的密鑰,無論是測試它與in或使用.get()方法來獲取值或默認:

if search_key in countryDict: 
    answer = [['country','code'], [search_key, countryDict[search_key]] 
else: 
    answer = [['country','code'], ['INVALID CODE', 'n/a']] 

或使用:

country = countryDict.get(search_key) 
if country: 
    answer = [['country','code'], [country, search_key]] 
else: 
    answer = [['country','code'], ['INVALID CODE', 'n/a']]