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]
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()