2013-07-17 46 views
4

我有一個接受字典作爲參數(從另一個函數返回)的函數。這個函數應該要求字符串作爲輸入,並查看字典中的每個元素,看看它是否在那裏。字典基本上是三字母縮寫:國家即:AFG:阿富汗等等。如果我要把字符串放在'sta'中,它應該將任何具有像United States STAtes,AfghaniSTAn,coSTA rica等片段的國家添加到已初始化的空列表中,然後返回該列表。否則,它返回[NOT FOUND]。返回的列表應該如下所示:[['Code','Country'],['USA','United States'],['CRI','Costa Rica'],['AFG','Afganistan']]]等等。這裏是我的代碼看起來像迄今:需要遍歷字典才能找到字符串片段

def findCode(countries): 
    some_strng = input("Give me a country to search for using a three letter acronym: ") 
    reference =['Code','Country'] 
    code_country= [reference] 
    for key in countries: 
     if some_strng in countries: 
      code_country.append([key,countries[key]]) 
    if not(some_strng in countries): 
     code_country.append(['NOT FOUND']) 
    print (code_country) 
    return code_country 

我的代碼只是不斷返回[ '未找到']

回答

5

您的代碼:

for key in countries: 
    if some_strng in countries: 
     code_country.append([key,countries[key]]) 

應該是:

for key,value in countries.iteritems(): 
    if some_strng in value: 
     code_country.append([key,countries[key]]) 

您需要檢查字符串的每個值,假定您的國家在值中而不是密鑰。

而且最終return語句:

if not(some_strng in countries): 
    code_country.append(['NOT FOUND']) 

應該是這樣的,有很多種方法來檢查:

if len(code_country) == 1 
    code_country.append(['NOT FOUND']) 
+4

你的意思'countries.iteritems()'? –

+0

運行它檢查,我可能有@JonClements **編輯**是的,我做了 – Stephan

+0

而不是'如果'只是'返回code_country如果code_country其他['未找到'] – Esenti