Separate output for each iteration

Viewed 40
def calculate_average_grade(grades_dictionary):
        grades_avg = {}
        for key in grades_dictionary.keys():
                average = sum(grades_dictionary[key]) / len(grades_dictionary[key])
                grades_avg[key] = average
        return grades_avg
grades_dictionary = readGrade
avg_grade = calculate_average_grade(grades_dictionary)
print(f' {readGrade} => {avg_grade}')

I need this code to print output separately like {"XYZ": [3,2,4,5]} ==> {"XYZ": 3.5}

My code outputs together like-

{'PQR': [4.0, 4.0, 4.5, 2.5, 4.5, 3.5], 'LMN': [4.0, 4.0, 3.0, 3.0, 3.0, 3.5]}) => {'PQR': 3.8333333333333335, 'LMN': 3.4166666666666665}
1 Answers

I would restructure your code. Make a function that computes averages, and run that in a loop that prints averages. The alternative would be to turn your function into a generator, and run that in a loop, but that would just make it unnecessarily complicated.

Something like this should do the trick:

def calculate_average_grade(grades):
    return sum(grades) / len(grades)

for key, grades in readGrade.items():
    print(f'{{{key!r}: {grades}}} => {{{key!r}: {calculate_average_grade(grades)}}}')

When you have an f-string, curly braces that you want to print literally have to be escaped by doubling them up. If you want quotes around a string in the format, print it using repr instead of str, by using the !r specifier.

With this formulation, you keep the formatting and the computation separate in your code, making at least the latter reusable, since it's not tied to a particular data format.

Related