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.
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. 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
.
>>> studentScores[student + classname] = score
>>> studentScores
>>> {'foobar': 0}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.