python - 如何根据键对字典值求和?

标签 python dictionary

我有一个字典列表如下:

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'}]

我正在尝试对每个给定类(class)的每个 student_id 的分数求和。例如 1 号学生在类(class) 1 中的总分将是 42.6,等等。理想情况下,我会创建一个新的干净列表,其中只有每个学生每门类(class)的总分。

我想到的一件事是编写一个迭代,如果前一项的学生和类(class) ID 与下一项相匹配,则将其相加:

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) 

我认为这不是解决问题的好方法。

最佳答案

如果您使用 defaultdict您可以使用 (student_id, course_id) 的元组作为 key 。然后你可以随时添加。如果你想要一个列表在最后,这是一个简单的列表理解:

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()]

这给了你:

[{'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}]

关于python - 如何根据键对字典值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68719422/

相关文章:

python:递归更新字典的值

c# - .NET 字典中的元素是连续的吗?

javascript - MapBox dragging.disable 函数阻止页面在移动设备上滚动

c# - 用 c# 编写 mp3 播放器,使用字典或数组作为元数据?

python - 如何在Python中删除中文标点符号

python - 子进程 Popen 返回一个空字符串作为 communications()[0].split ('\n' 上的最后一个列表成员

使用 pymodbus 模块的 Python Modbus 服务器

python - 为什么不同的格式方法在 Python 中表现不同?

python - 要列出的命名元组字符串

c++ - 我是否以正确的方式插入到 STL map 中?它不会泄漏内存吗?