尝试在嵌套字典中查找唯一值的总和。 (请参见示例!)

时间:2018-11-14 00:11:02

标签: python dictionary nested

比方说,我有这个变量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']

任何帮助或建议,我们将不胜感激!谢谢。

3 个答案:

答案 0 :(得分:7)

您可以使用字典来跟踪每个名称的分数:

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}

答案 1 :(得分:2)

data = {}
for item in list_1: # for each item in our list
   # set our category to its existing value (or 0) + the new score
   data[item['group']['name']] = item['score'] + data.get(item['group']['name'],0)

print(data) # output = {'History': 5, 'Math': 20, 'Ceramics': 18}

然后您可以使用格式字符串轻松打印

for group_name,scores_summed in data.items():
    print("Totals for {group_name} = {scores_summed}".format(group_name=group_name,scores_summed=scores_summed))

答案 2 :(得分:0)

@JacobIRR和@JoranBeasley的答案都很好,可以选择以下方法:

data = [
    {"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}}
]

result = {}
scores = iter((e['group']['name'], e['score']) for e in data)
for name, score in scores:
    result[name] = result.get(name, 0) + score

print(result)

输出

{'Ceramics': 18, 'History': 5, 'Math': 20}