首页 > 解决方案 > 试图在嵌套字典中查找唯一值的总和。(见例子!)

问题描述

假设我有这个变量 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']

任何帮助或建议表示赞赏!谢谢。

标签: pythondictionarynested

解决方案


您可以使用 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}


推荐阅读