所以我有这些值的文件:
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
像这样存储到字典中:
{'ARG': (40, 18, 24, 28), 'ALG': (15, 5, 2, 8), 'AFG': (13, 0, 0, 2)}
我有一个让用户按下键的函数,它应该返回包含数字的元组。
但是,如果我输入 AFG,我会得到:
Traceback (most recent call last):
File "C:\Users\username\Dropbox\Programming\Python\Project3.py", line 131, in <module>
main()
File "C:\Users\username\Dropbox\Programming\Python\Project3.py", line 110, in main
findMedals(countryDictionary, MedalDictionary)
File "C:\Users\username\Dropbox\Programming\Python\Project3.py", line 88, in findMedals
answer.append([medalDict[medalCount]])
KeyError: (13, 0, 0, 2)
如您所见,KeyError 为输入的键提供了正确的值,但为什么它仍然在抱怨呢?KeyError 不意味着密钥不存在吗?
我的代码:
def findMedals(countryDict, medalDict):
search_str = input('What is the country you want information on? ')
for code, medalCount in medalDict.items():
if search_str in code:
answer.append([medalDict[medalCount]])
else:
answer = ['No Match Found']