-3

How can I save the average of each individual in the order of upwardness of the average score with the person's name in a dictionary?

Finally, save the top 3 highs in a list called top?

import csv
from statistics import mean

with open('grades.csv') as f:
      reader = csv.reader(f)
      for row in reader:
            #print(row)
            name = row[0]
            grades = []
            for grade in row[1:]:
                  grades.append(int(grade))


            print('Average of %s --> %f' % (name, mean(grades)))
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Ali Zareei
  • 23
  • 5
  • did you try to "keep" (not save) your results in a dictionary ? -- please update your code to reflect this. – Edwin van Mierlo May 15 '18 at 07:00
  • Well, my problem is exactly the same – Ali Zareei May 15 '18 at 07:04
  • Exactly, I can not store the average of each person with his name in a dictionary in descending order of magnitude, respectively. – Ali Zareei May 15 '18 at 07:05
  • 1
    There are two reasons, first is that you are not using any dictionary in your code, and second is that a dictionary is that a dictionary is not ordered in python (unless you user ordereddict. You can read this good answer https://stackoverflow.com/questions/22393661/ordered-dictionary-in-python – nacho May 15 '18 at 07:10
  • Is there any way I can put the name of any person in my dictionary with my grade? – Ali Zareei May 15 '18 at 07:17

1 Answers1

0

Here's my example, is that what you wanted?

from statistics import mean

items = [
    ['John', 1,2,3,5,21,2,3,2,1,2,5],
    ['Alice', 5,31,6,73,4,2,1],
    ['Bill', 7,4,6,78,3,1,2,21],
    ['Sarah', 2,3,5,6,4,7,7],
    ['Martin', 2,4,6,3,8,2,3,3],
]

some_dict = {}
for row in items:
    name = row[0]
    grades = list(map(int, row[1:]))

    print('Average of %s --> %f' % (name, mean(grades)))
    some_dict.update({name: {'grades': grades, 'mean': mean(grades)}})

print(some_dict)
print(sorted(some_dict.items()))

Output:

Average of John --> 4.272727
Average of Alice --> 17.428571
Average of Bill --> 15.250000
Average of Sarah --> 4.857143
Average of Martin --> 3.875000
{'John': {'grades': [1, 2, 3, 5, 21, 2, 3, 2, 1, 2, 5], 'mean': 4.2727272727272725}, 'Alice': {'grades': [5, 31, 6, 73, 4, 2, 1], 'mean': 17.428571428571427}, 'Bill': {'grades': [7, 4, 6, 78, 3, 1, 2, 21], 'mean': 15.25}, 'Sarah': {'grades': [2, 3, 5, 6, 4, 7, 7], 'mean': 4.857142857142857}, 'Martin': {'grades': [2, 4, 6, 3, 8, 2, 3, 3], 'mean': 3.875}}
[('Alice', {'grades': [5, 31, 6, 73, 4, 2, 1], 'mean': 17.428571428571427}), ('Bill', {'grades': [7, 4, 6, 78, 3, 1, 2, 21], 'mean': 15.25}), ('John', {'grades': [1, 2, 3, 5, 21, 2, 3, 2, 1, 2, 5], 'mean': 4.2727272727272725}), ('Martin', {'grades': [2, 4, 6, 3, 8, 2, 3, 3], 'mean': 3.875}), ('Sarah', {'grades': [2, 3, 5, 6, 4, 7, 7], 'mean': 4.857142857142857})]
Konstantin
  • 547
  • 4
  • 11