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
  • The error is on line 57 but you have not provided 57 lines of code, so I cannot determine which of these lines the error is coming from. Please comment on the line that is giving the error. – Brendan Lynn Commented Nov 23, 2024 at 5:12
  • You wrote 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
  • What do you expect to happen if the grade is neither A, B, C, D nor F? – SIGHUP Commented Nov 23, 2024 at 8:02
Add a comment  | 

1 Answer 1

Reset to default 0

You 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