【问题标题】:Trying to find sums of unique values within a nested dictionary. (See example!)试图在嵌套字典中查找唯一值的总和。 (见例子!)
【发布时间】:2019-04-16 21:28:29
【问题描述】:

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

感谢任何帮助或建议!谢谢。

【问题讨论】:

  • 尝试在代码读取时完全处理每个项目。也许让group_names_list 成为一个组名字典,然后是一个带有分数的作业列表。当您阅读新项目时,请将[title, score] 附加到此列表中。完全处理完输入后,对字典进行第二次循环,将每个组的所有分数相加。所以group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

标签: python dictionary nested


【解决方案1】:

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

【讨论】:

    【解决方案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))
    

    【讨论】:

      【解决方案3】:

      @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}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-01
        • 1970-01-01
        • 2022-10-12
        • 1970-01-01
        • 2013-10-23
        • 2012-12-23
        • 2022-06-15
        • 2021-02-05
        相关资源
        最近更新 更多