python - 试图在嵌套字典中查找唯一值的总和。(见例子!)
问题描述
假设我有这个变量 list_1 ,它是一个字典列表。每个字典都有一个嵌套字典,称为“组”,其中包含一些信息,包括“名称”。
我要做的是对每个唯一组名的分数求和。
所以我正在寻找类似于以下内容的输出:
(陶瓷)总分=(18)
(数学)总分=(20)
(历史)总分=(5)
我在括号中包含上述信息,因为无论列表中的项目数量或代表的唯一组数量如何,我都希望此代码能够正常工作。
list_1 变量:
list_1 = [
{"title" : "Painting",
"score" : 8,
"group" : {"name" : "Ceramics",
"id" : 391}
},
{"title" : "Exam 1",
"score" : 10,
"group" : {"name" : "Math",
"id" : 554}
},
{"title" : "Clay Model",
"score" : 10,
"group" : {"name" : "Ceramics",
"id" : 391}
},
{"title" : "Homework 3",
"score" : 10,
"group" : {"name" : "Math",
"id" : 554}
},
{"title" : "Report 1",
"score" : 5,
"group" : {"name" : "History",
"id" : 209}
},
]
我的第一个想法是创建一个新的列表变量并附加每个唯一的组名。这是代码。但这是否有助于最终找到每个分数的总和?
group_names_list = []
for item in list_1:
group_name = item["group"]["name"]
if group_name not in group_names_list:
group_names_list.append(group_name)
这给了我 group_names_list 的值:
['Ceramics','Math','History']
任何帮助或建议表示赞赏!谢谢。
解决方案
您可以使用 dict 来跟踪每个名称的分数:
score_dict = dict()
for d in list_1:
name = d['group']['name']
if name in score_dict:
score_dict[name] += d['score']
else:
score_dict[name] = d['score']
print(score_dict)
结果: {“陶瓷”:18,“数学”:20,“历史”:5}
推荐阅读
- javascript - 如何在 typescript/javascript 中从字符串转换为表情符号
- c# - 关闭选项卡控件时关闭相应的 ProcessStart 应用程序
- javascript - Chrome 扩展 content.js 文件可以更新 draft.js 文本编辑器吗?
- java - 聊天消息应用程序崩溃(使用 Firebase)
- asp.net-core-mvc - 自己的基于角色的系统 Angular 6 和 ASP.NET Core 2.1
- javascript - 将组件资产放在自己的目录中
- reactjs - 使用 Gatsby 处理 URL 参数
- javascript - 对象未出现在画布主体负载上
- android - 替换片段不显示整个片段
- c++ - 使用行主矩阵的特征矩阵乘法性能