简体   繁体   English

扩展时的字典KeyError

[英]Dictionary KeyError when extending

I'm trying to extend the dictionary when a user completes the quiz. 当用户完成测验时,我正在尝试扩展字典。 I'm looking to store the last three scores only for a user but I get an KeyError when I try to add it to the empty dictionary and a unhashable list error when I try to implement the score as a list. 我期待到最后三轮成绩仅存储用户,但我得到一个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)

As noted in comments, the problem is on this line: 如评论中所述,问题出在这条线上:

studentScores[student + classname, score]

What this line does: It creates a tuple of (student + classname, score) and uses that tuple as a key to the dictionary. 这行的作用:它创建的元组 (student + classname, score)并使用元组作为重点字典。 And since that key does not exist, it raises an exception. 并且由于该键不存在,因此引发了异常。

>>> 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)

Instead, you want to use just student + classname as the key and assign to it the value of score . 相反,您只想使用student + classname作为键,并为其分配 score的值。

>>> studentScores[student + classname] = score
>>> studentScores
>>> {'foobar': 0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM