csv reading into a dictionary of names and averages (python)

Viewed 63

I'm new to programming. I want to calculate the average of numbers from a csv file and have a dictionary of names and average numbers. I can have a dictionary for a row (just one name and his average), but I cannot find a solution to save them to a greater dictionary. To be clear, I can just have a dictionary of one key and value. You can see the results here:

import csv
from statistics import mean

with open('/Exercise/moyen.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        name = row[0]
        grades_list = list()
        for grade in row[1:]:
            grades_list.append(float(grade))
        average = mean(grades_list)
        
        attributes = {
           name: average
        }
                
        print (attributes)

# {'hooman': 13.642857142857142}
# {'soly': 15.714285714285714}
# {'mammad': 14.857142857142858}
# {'ashkan': 16.285714285714285}

I need to have a dictionary with all these names and values together. I think I don't have a good understanding of csv reading loop.

1 Answers

Initialise your attributes dictionary before with open(). So put attributes = {} as your first line of code after your imports. Then change your attributes = {name:average} line to attributes[name] = average.

Instead of setting a new dictionary each time with one key and value, this will add to the dictionary each time, so at the end you'll have all the results together.

Related