Search code examples
pythontypeerrorindices

TypeError: string indices must be integers, not 'str'.... accessing values in a dictionary


it works once but in the next line it will have the error in the title.

Traceback (most recent call last):
  File "c:\Users\User\AppData\Local\tmc\vscode\mooc-programming-24\part07-15_who_cheated_2\src\who_cheated_2.py", line 51, in <module>    
    print(final_points())
          ^^^^^^^^^^^^^^
  File "c:\Users\User\AppData\Local\tmc\vscode\mooc-programming-24\part07-15_who_cheated_2\src\who_cheated_2.py", line 29, in final_points
    print(maxs>wank[line[0]])
               ~~~~^^^^^^^^^
TypeError: string indices must be integers, not 'str'
# Write your solution here

from datetime import timedelta,datetime
import csv


def final_points():
    wank = {}
    with open("start_times.csv") as rocky:
        for line in csv.reader(rocky,delimiter=";"):
            pol = datetime.strptime(line[1],"%H:%M")
            wank[line[0]] = pol

                    
    students = {}
    rankings = {"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0}
    
    
    with open("submissions.csv") as monks:
        for line in csv.reader(monks,delimiter=";"):
            rap = datetime.strptime(line[3],"%H:%M")
            
            maxs = rap - timedelta(hours=3)
            print(line[0])
            print(maxs>wank[line[0]])
            if maxs>wank[line[0]]:
                continue
            
            
            
            wank = line[1]
            if line[0] not in students:
                students[line[0]] = rankings
            print(students)
            
            if students[line[0]][line[1]]<int(line[2]):
                students[line[0]][line[1]] = int(line[2])
            
        for key in students:
            students[key] = sum(students[key].values())

    
    return students


if __name__ == "__main__":
    print(final_points())

thats the code and the files are like this

start times

matti;13:33
erkki;15:13
antti;15:49
emilia;13:37
henrik;15:01
arto;17:01
esko;14:24
kjell;13:34
jyrki;16:12
etc..

submissions format is like:

arto;1;4;19:12
erkki;2;2;16:03
matti;7;3;16:21
jyrki;1;3;17:43
etc...

i tried printing so thats why i know that it worked once in arto but in erkki it stops because of that line[0] thing i dont know why


Solution

  • There is a line in your code that causes this error and converts wank from a dictionary to a string. Here is the line :

    wank = line[1]
    

    And you don't use the variable wank after this line in your code. So probably removing this line will address the issue.