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

我认为这可能与 for 循环中的 else 语句有关,但将其带出循环似乎也无济于事。

4

1 回答 1

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']]
于 2013-07-19T13:20:58.440 回答