[英]need to iterate through dictionary to find slice of string
我有一個函數接受字典作為參數(從另一個有效的函數返回)。 這個函數應該要求輸入一個字符串,並查看字典中的每個元素,看看它是否在那里。 字典基本上是三字母縮寫:國家即:AFG:阿富汗等等。 如果我將'sta'作為我的字符串,它應該將任何具有該團隊STATY,AfghaniSTAn,coSTA rica等片段的國家附加到初始化的空列表中,然后返回所述列表。 否則,它返回[未找到]。 返回列表應如下所示:[['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
我的代碼一直在返回['找不到']
你的代碼:
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]])
您需要檢查字符串的每個值,假設您的國家/地區位於值而不是鍵中。
您最后的退貨聲明:
if not(some_strng in countries):
code_country.append( ['NOT FOUND'])
應該是這樣的,有很多方法可以檢查:
if len(code_country) == 1
code_country.append( ['NOT FOUND'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.