pythondictionarykeyerror

Key error when I try to iterate on dictionary


I have the file text.txt with following data

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

I tried to run a code to copy and sum the points of third column, but I have following error regarding the key on the dictionary:

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'

I guess the error in on line : data[student] += points

However, I do not know how to resolve it Please, someone can give me an advice?


Solution

  • data[student] += points is equal to data[student] = data[student] + points, so it will raise key error because data is an empty dict and it can't find the corresponding key.

    You need to insert/update the data dict then add the value to point:

    data = {}
    points = 0
    f = open('text.txt')
    lines = f.readlines()
    f.close()
    for line in lines:
        columns = line.split()
        student = f'{columns[0]} {columns[1]}'
        point = float(columns[2])
        data[student] = point
        points += point
    for student in sorted(data):
        print(f'{student}\t {data[student]}')
    

    Or:

    data = {}
    
    with open('text.txt') as file:
        for line in file:
            firstname, lastname, point = line.split()
            data[f'{firstname} {lastname}'] = float(point)
    
        points = sum(data.values())
    
    for student in sorted(data):
        print(f'{student}\t {data[student]}')