Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum dictionary values based on keys?

I have a list of dictionary as below:

data = [{'student_id': '1','mark': 7.8,'course_id': '1',},
        {'student_id': '1','mark': 34.8,'course_id': '1'},
        {'student_id': '1','mark': 12.8,'course_id': '2'},
        {'student_id': '1','mark': 39.0,'course_id': '2'},
        {'student_id': '1','mark': 70.2,'course_id': '3'},
        {'student_id': '2','mark': 7.8,'course_id': '1'},
        {'student_id': '2','mark': 34.8,'course_id': '1'}]

I am trying to sum the marks per student_id per given course. such as the student no.1's total marks from course 1 will be 42.6, etc. Ideally, I would create a new clean list with only the total marks per students per a course.

One thing came to my mind was to write an iteration to sum add it each if the student and course id from the previous item matches the next one:

for i in range(len(data)-1):
    if data[i]['course_id'] == data[i+1]['course_id'] and data[i]['student_id'] == data[i+1]['student_id']:
        data[i+1]['sum_mark'] = round(float(data[i]['mark'])+float(data[i+1]['mark']),3) 

I don't think this is a good way to approach the problem.

like image 836
Edfern Avatar asked Apr 25 '26 14:04

Edfern


1 Answers

If you use a defaultdict you can use a tuple of (student_id, course_id) for the key. Then you can just add to this as you go. If you want a list at the end, it's a simple list comprehension:

from collections import defaultdict

totals = defaultdict(float)

for d in data:
    totals[(d['student_id'], d['course_id'])] += d['mark']
    
[{'student_id':s_id, 'course_id': c_id, 'total': round(total, 3)} 
 for (s_id, c_id), total in totals.items()]

Which gives you:

[{'student_id': '1', 'course_id': '1', 'total': 42.6},
 {'student_id': '1', 'course_id': '2', 'total': 51.8},
 {'student_id': '1', 'course_id': '3', 'total': 70.2},
 {'student_id': '2', 'course_id': '1', 'total': 42.6}]
like image 169
Mark Avatar answered Apr 28 '26 03:04

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!