Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am having trouble trying to fix TypeError: string indices must be integers

Grades.txt file

I am currently trying to finish a assignment but I am confused on how to fix this error. I am creating a program that will analyzes grades from a file and should calculate the
average score for each distinct section (given). I receive the error for

sections[sec]["total"] = grade[grade]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

grades = {'A': 100, 'B': 89, 'C': 79, 'D': 74, 'F': 69}

# this section reads the file


def calculate_average():
    file = open("grades.txt", "r")
    sections = {}
    for line in file:
        [_, sec, grade] = line.split("\t")
        grade = grade.strip()
        if sec in sections:
            sections[sec]["count"] += 1
            sections[sec]["total"] += grade[grade]
        else:
            sections[sec] = {}
            sections[sec]["count"] = 1
            sections[sec]["total"] = grade[grade]
    file.close()

# This section calculates the average data based on file

    for sec, secdata in sections.items():
        avg = secdata[" total "] / secdata[" count"]
        print(" {0} : {1}".format(sec, round(avg, 2)))


if __name__ == "__main__":
    calculate_average()

>Solution :

It looks like you are trying to access the value of the grade dictionary by using the value of the grade variable as a key. This won’t work because the keys of the grade dictionary are strings (e.g. ‘A’, ‘B’, ‘C’), but the value of the grade variable is also a string (e.g. ‘A’, ‘B’, ‘C’), so you are trying to use a string as an index for a dictionary.

To fix this error, you should use the grade variable directly to access the value in the grade dictionary, like this:

sections[sec]["total"] += grades[grade]

This will add the value associated with the grade string in the grades dictionary to the total field in the sections dictionary.

Here is the updated code with this change:

grades = {'A': 100, 'B': 89, 'C': 79, 'D': 74, 'F': 69}

# this section reads the file


def calculate_average():
    file = open("grades.txt", "r")
    sections = {}
    for line in file:
        [_, sec, grade] = line.split("\t")
        grade = grade.strip()
        if sec in sections:
            sections[sec]["count"] += 1
            sections[sec]["total"] += grades[grade]
        else:
            sections[sec] = {}
            sections[sec]["count"] = 1
            sections[sec]["total"] = grades[grade]
    file.close()

# This section calculates the average data based on file

    for sec, secdata in sections.items():
        avg = secdata[" total "] / secdata[" count"]
        print(" {0} : {1}".format(sec, round(avg, 2)))


if __name__ == "__main__":
    calculate_average()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading