Skip to content Skip to sidebar Skip to footer

How To Get An Average From A Row Then Make A List Out Of It

If I have a csv data that gives two row values of: years grades 2001 98 2001 75 2008 100 2003 57 2008 50 I have more values but I will try to explain what I am trying to get

Solution 1:

Why not build a dictionary of grades with the key being each year:

from collections import defaultdict
grades = defaultdict(lambda: [])

withopen('grades.csv', 'r') as f:
    year, grade = (s.strip() for s in row.split(','))
    grades[year].append(grade)

Then print the averages:

for y, g in grades:
    print('{}: {}', y, sum(g) / float(len(g)))

Solution 2:

you can use defaultdict to form a dictionary whose value (grade) is a list , key is year, then append grade to same year in the dictionary, after that data will be a defaultdict(list):

defaultdict(<type'list'>, {'2003': ['57'], '2008': ['100', '50'], '2001': ['98', '75']})

Then, you can for loop the key and value to calculate the average:

from collections import defaultdict
data = defaultdict(list)
average_grade_by_year = dict()
withopen('grades.csv', 'r') as filing:
    next(filing)
    for row in filing:
        year, grade = (s.strip() for s in row.split(','))
        data[year].append(grade)
    for k, v in data.items():
        average_grade_by_year[k] = float(sum(int(x) for x in v))/len(v)
print(average_grade_by_year)

average_grade_by_year will be: {'2001': 86.5, '2003': 57.0, '2008': 75.0}

Post a Comment for "How To Get An Average From A Row Then Make A List Out Of It"