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
我的代碼只是不斷返回[ '未找到']
你的意思'countries.iteritems()'? –
運行它檢查,我可能有@JonClements **編輯**是的,我做了 – Stephan
而不是'如果'只是'返回code_country如果code_country其他['未找到'] – Esenti