如何在这个代码python中定义键

时间:2015-03-20 19:02:58

标签: python

我希望我的代码能够为每个学生记录最新的3个分数,当添加第4个分数时,它将覆盖最旧的分数并将其替换为新的分数。我需要布局:

f,7,8,9

我创建了这段代码,但是当我运行它时,它会要求我定义密钥。这是我的代码:

pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME  = "Class1.txt"
MAX_SCORES = 3

try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists

actualScoresTable = dict()

for line in scoresFile:
    tmp = line.replace("\n","").split(",")
    actualScoresTable[tmp[0]]=tmp[1:]
scoresFile.close()


if pname not in actualScoresTable.keys():
    actualScoresTable[pname] = [correct]
else:
    actualScoresTable[pname].append(correct)
    if MAX_SCORES < len(actualScoresTable[pname]):
            actualScoresTable[key].pop(0)


scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for key in actualScoresTable.keys():
    scoresFile.write("%s,%s\n" % (key, ','.join(actualScoresTable[key])))
scoresFile.close()

当我运行代码时,它告诉我没有定义'key'。 我如何定义密钥? 我被告知它需要是一个元组,但我不知道如何使它和我的代码工作。

Traceback (most recent call last):
  File "C:\Users\Milan\Documents\Python\Task 3 tries\3 scores.py", line 23, in <module>
    actualScoresTable[key].pop(0)
NameError: name 'key' is not defined

1 个答案:

答案 0 :(得分:1)

错误在这一行:

actualScoresTable[key].pop(0)

在此代码之后,您才能定义密钥。 我想你想要的是actualScoresTable[pname].pop(0)