当用户完成测验时,我试图扩展字典。我希望仅为用户存储最后三个分数,但当我尝试将其添加到空字典时我得到KeyError
,当我尝试将分数作为列表实现时,我得到一个不可用的列表错误
studentScores = {}
def quiz():
print("WELCOME TO THE MATH QUIZ\n")
global student
student = input("What is your name? ")
global classname
classname = input("Which class are you in? (1, 2, 3) ")
global score
score = 0
def addDict():
global student
global classname
global score
score = str(score)
studentScores[student + classname, score]
print(studentScores)
答案 0 :(得分:1)
如评论中所述,问题出现在这一行:
studentScores[student + classname, score]
这一行的作用:它创建(student + classname, score)
的元组,并使用该元组作为字典的键。由于该密钥不存在,因此会引发异常。
>>> student = "foo"
>>> classname = "bar"
>>> score = 0
>>> studentScores = {}
>>> studentScores[student + classname, score]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ('foobar', 0)
相反,您只想使用student + classname
作为键,将赋值为score
。
>>> studentScores[student + classname] = score
>>> studentScores
>>> {'foobar': 0}