[英]Dictionary KeyError when extending
当用户完成测验时,我正在尝试扩展字典。 我期待到最后三轮成绩仅存储用户,但我得到一个KeyError
,当我尝试将其添加到空字典和unhashable列表错误,当我尝试实施比分为列表。
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)
如评论中所述,问题出在这条线上:
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.