当我尝试迭代字典时出现关键错误

问题描述 投票:0回答:1

我有包含以下数据的文件text.txt

Oscar    Morera    90
Maria    Esquivel  95 
Lucia    Benavides 80
Javier   Miranda   85
Alonso   Gonzalez  75

我尝试运行代码来复制和求和第三列的点,但是关于字典上的键出现以下错误:

data = { }
points = 0
f = open("text.txt")
lines=f.readlines()
f.close()
for i in range(len(lines)):
        # Make the line
        line = lines[i]
        # Divide it among columns.
        columns = line.split()
        # Key from student: name, last name and calification
        student = columns[0] + columns[1] + columns[2] 
        # Make float columns 2 (points)
        points = float(columns[2])
        # Iterate throw the data
        data[student] += points
for student in sorted(data.keys()):
        print(student,'\t', data[student])
Traceback (most recent call last):
  File "C:\Users\Admin\Desktop\Test3.py", line 17, in <module>
    data[student] += points
KeyError: 'OscarMorera90'

我猜网上有错误:

data[student] += points

但是我不知道如何解决 请问有人可以给我建议吗

python dictionary keyerror
1个回答
-1
投票

也许这就是您正在寻找的:

data = { }
points = 0
f = open("text.txt")
lines=f.readlines()
f.close()
for i in range(len(lines)):
        # Make the line
        line = lines[i]
        # Divide it among columns.
        columns = line.split()
        # Key from student: name, last name and calification
        student = columns[0] + columns[1] + columns[2] 
        # Make float columns 2 (points)
        points = float(columns[2])
        # Iterate throw the data
        data[student] =  points
        
for student in sorted(data.keys()):
        print(student,'\t', data[student])\

输出:

AlonsoGonzalez75         75.0
JavierMiranda85          85.0
LuciaBenavides80         80.0
MariaEsquivel95          95.0
OscarMorera90            90.0
© www.soinside.com 2019 - 2024. All rights reserved.