admin管理员组文章数量:1122846
I need to write a program that reads student grades from a text file. Each line starts with student ID, then a Section Number, then a letter grade (A, B, C, D or F).
My output needs to show the average grade number for each section, and my plan was to use a dictionary to map the grades to section to keep a running total for each section and be divided later by the number of entries in that section.
I am struggling to figure out how to add the current lines grade to the corresponding section in the dictionary
My code is below, as well as this TypeError I am experiencing:
line 57, in TypeError: unsupported operand type(s) for +: 'set' and 'int'
I have tried reading into a dictionary to key each section number with a running total number grade, which will then be divided by the number of entries to get the average.
`#Open the grades file for reading and create a dictionary to hold section/section grade pairs
file = open("grades.txt",'r')
total_section_grades = dict()
#Use for loop to iterate through each line of the grades.txt file
#separating the letter grade with split function
for line in file:
pupil_ID,section_num,alpha_grade = line.strip().split("\t")
#Default numeric grade to 0 for each line in file
num_grade = 0
#Conditionals to convert letter grades to numbers
if alpha_grade == 'A':
alpha_grade = 100
elif alpha_grade == 'B':
alpha_grade = 89
elif alpha_grade == 'C':
alpha_grade = 79
elif alpha_grade == 'D':
alpha_grade = 74
elif alpha_grade == 'F':
alpha_grade = 69
#If section number exists in total_section_grades dictionary then
#update that section with num_grade variable
#If section number does not exist then create new section number key and
#add num_grade to dictionary
if section_num in total_section_grades:
total_section_grades[section_num] = total_section_grades[section_num] + num_grade
else:
total_section_grades[section_num] = {num_grade}
#Close text file
file.close()
#Calculate average numerical grade for each section
for current_section, grade_sum in total_section_grades.items():
average = sum(grades_sum)/len(grades_sum)
print(f"{current_section} average: {average}")`
I need to write a program that reads student grades from a text file. Each line starts with student ID, then a Section Number, then a letter grade (A, B, C, D or F).
My output needs to show the average grade number for each section, and my plan was to use a dictionary to map the grades to section to keep a running total for each section and be divided later by the number of entries in that section.
I am struggling to figure out how to add the current lines grade to the corresponding section in the dictionary
My code is below, as well as this TypeError I am experiencing:
line 57, in TypeError: unsupported operand type(s) for +: 'set' and 'int'
I have tried reading into a dictionary to key each section number with a running total number grade, which will then be divided by the number of entries to get the average.
`#Open the grades file for reading and create a dictionary to hold section/section grade pairs
file = open("grades.txt",'r')
total_section_grades = dict()
#Use for loop to iterate through each line of the grades.txt file
#separating the letter grade with split function
for line in file:
pupil_ID,section_num,alpha_grade = line.strip().split("\t")
#Default numeric grade to 0 for each line in file
num_grade = 0
#Conditionals to convert letter grades to numbers
if alpha_grade == 'A':
alpha_grade = 100
elif alpha_grade == 'B':
alpha_grade = 89
elif alpha_grade == 'C':
alpha_grade = 79
elif alpha_grade == 'D':
alpha_grade = 74
elif alpha_grade == 'F':
alpha_grade = 69
#If section number exists in total_section_grades dictionary then
#update that section with num_grade variable
#If section number does not exist then create new section number key and
#add num_grade to dictionary
if section_num in total_section_grades:
total_section_grades[section_num] = total_section_grades[section_num] + num_grade
else:
total_section_grades[section_num] = {num_grade}
#Close text file
file.close()
#Calculate average numerical grade for each section
for current_section, grade_sum in total_section_grades.items():
average = sum(grades_sum)/len(grades_sum)
print(f"{current_section} average: {average}")`
Share
Improve this question
edited Nov 23, 2024 at 19:31
Brendan Lynn
4682 silver badges15 bronze badges
asked Nov 23, 2024 at 5:04
Churro ManChurro Man
11 bronze badge
3
|
1 Answer
Reset to default 0You should be using a lookup (dictionary) to map the grades to their respective values. Also, if you use collections.defaultdict you'll find the updating of a summary dictionary much easier.
from collections import defaultdict
grade_map = {
"A": 100,
"B": 89,
"C": 79,
"D": 74,
"F": 69
}
summary = defaultdict(list)
with open("grade.txt") as file:
for line in map(str.strip, file):
try:
_, section, grade = line.split("\t")
summary[section].append(grade_map[grade])
except KeyError:
print(f"Unknown grade in {line}")
except ValueError:
print(f"Malformed line {line}")
for section, scores in summary.items():
average = sum(scores) / len(scores)
print(f"{section} average: {average:.2f}")
本文标签: How to perform addition to entries in Python dictionary variableStack Overflow
版权声明:本文标题:How to perform addition to entries in Python dictionary variable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736299590a1930510.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
total_section_grades[section_num] = {num_grade}
. Why did you use the curly braces? That makes that entry a set containing one item. Just remove the braces, and it should do what you want. And you could use a dictionary to do the grade-to-point-value lookup. – Tim Roberts Commented Nov 23, 2024 at 5:17