Trying to find sums of unique values within a nested dictionary. (See example!)










6















Let's say I have this variable list_1 which is a list of dictionaries.
Each dictionary has a nested dictionary called "group" in which it has some information including "name".



What I'm trying to do is to sum the scores of each unique group name.



So I am looking for an output similar to:



Total Scores in (Ceramics) = (18)

Total Scores in (Math) = (20)

Total Scores in (History) = (5)



I have the above info in parenthesis because I would like this code to work regardless of the amount of items in the list, or amount of unique groups represented.



The list_1 variable:



 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
,

]


My first idea was to create a new list variable and append each unique group name. Here's the code for that. But will this help in ultimately finding the sum of the scores for each one of these?



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)


This gives me the value of group_names_list as:



['Ceramics','Math','History']


Any help or suggestions are appreciated! Thanks.










share|improve this question

















  • 1





    Try to process each item completely as the code reads it. Maybe make the group_names_list a dictionary of group-name, and then a list of assignments with scores. As you read new items, append [title, score] to this list. Once you have processed the input fully, do a second loop over your dictionary, summing all the scores for each group. So group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

    – Kingsley
    Nov 14 '18 at 0:20















6















Let's say I have this variable list_1 which is a list of dictionaries.
Each dictionary has a nested dictionary called "group" in which it has some information including "name".



What I'm trying to do is to sum the scores of each unique group name.



So I am looking for an output similar to:



Total Scores in (Ceramics) = (18)

Total Scores in (Math) = (20)

Total Scores in (History) = (5)



I have the above info in parenthesis because I would like this code to work regardless of the amount of items in the list, or amount of unique groups represented.



The list_1 variable:



 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
,

]


My first idea was to create a new list variable and append each unique group name. Here's the code for that. But will this help in ultimately finding the sum of the scores for each one of these?



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)


This gives me the value of group_names_list as:



['Ceramics','Math','History']


Any help or suggestions are appreciated! Thanks.










share|improve this question

















  • 1





    Try to process each item completely as the code reads it. Maybe make the group_names_list a dictionary of group-name, and then a list of assignments with scores. As you read new items, append [title, score] to this list. Once you have processed the input fully, do a second loop over your dictionary, summing all the scores for each group. So group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

    – Kingsley
    Nov 14 '18 at 0:20













6












6








6








Let's say I have this variable list_1 which is a list of dictionaries.
Each dictionary has a nested dictionary called "group" in which it has some information including "name".



What I'm trying to do is to sum the scores of each unique group name.



So I am looking for an output similar to:



Total Scores in (Ceramics) = (18)

Total Scores in (Math) = (20)

Total Scores in (History) = (5)



I have the above info in parenthesis because I would like this code to work regardless of the amount of items in the list, or amount of unique groups represented.



The list_1 variable:



 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
,

]


My first idea was to create a new list variable and append each unique group name. Here's the code for that. But will this help in ultimately finding the sum of the scores for each one of these?



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)


This gives me the value of group_names_list as:



['Ceramics','Math','History']


Any help or suggestions are appreciated! Thanks.










share|improve this question














Let's say I have this variable list_1 which is a list of dictionaries.
Each dictionary has a nested dictionary called "group" in which it has some information including "name".



What I'm trying to do is to sum the scores of each unique group name.



So I am looking for an output similar to:



Total Scores in (Ceramics) = (18)

Total Scores in (Math) = (20)

Total Scores in (History) = (5)



I have the above info in parenthesis because I would like this code to work regardless of the amount of items in the list, or amount of unique groups represented.



The list_1 variable:



 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
,

]


My first idea was to create a new list variable and append each unique group name. Here's the code for that. But will this help in ultimately finding the sum of the scores for each one of these?



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)


This gives me the value of group_names_list as:



['Ceramics','Math','History']


Any help or suggestions are appreciated! Thanks.







python dictionary nested






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 0:11









Jane SmithJane Smith

333




333







  • 1





    Try to process each item completely as the code reads it. Maybe make the group_names_list a dictionary of group-name, and then a list of assignments with scores. As you read new items, append [title, score] to this list. Once you have processed the input fully, do a second loop over your dictionary, summing all the scores for each group. So group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

    – Kingsley
    Nov 14 '18 at 0:20












  • 1





    Try to process each item completely as the code reads it. Maybe make the group_names_list a dictionary of group-name, and then a list of assignments with scores. As you read new items, append [title, score] to this list. Once you have processed the input fully, do a second loop over your dictionary, summing all the scores for each group. So group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

    – Kingsley
    Nov 14 '18 at 0:20







1




1





Try to process each item completely as the code reads it. Maybe make the group_names_list a dictionary of group-name, and then a list of assignments with scores. As you read new items, append [title, score] to this list. Once you have processed the input fully, do a second loop over your dictionary, summing all the scores for each group. So group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

– Kingsley
Nov 14 '18 at 0:20





Try to process each item completely as the code reads it. Maybe make the group_names_list a dictionary of group-name, and then a list of assignments with scores. As you read new items, append [title, score] to this list. Once you have processed the input fully, do a second loop over your dictionary, summing all the scores for each group. So group_names_list["math"] = [ [ "Exam1",10 ], [ "Homework 3", 10 ] ]

– Kingsley
Nov 14 '18 at 0:20












3 Answers
3






active

oldest

votes


















7














You can use a dict to keep track of scores per name:



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)


RESULTS:
'Ceramics': 18, 'Math': 20, 'History': 5






share|improve this answer






























    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


    then you can print it easy enough using format strings



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





    share|improve this answer






























      0














      Both the answers of @JacobIRR and @JoranBeasley are great, as alternative you could do the following:



      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)


      Output



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





      share|improve this answer






















        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291314%2ftrying-to-find-sums-of-unique-values-within-a-nested-dictionary-see-example%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        7














        You can use a dict to keep track of scores per name:



        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)


        RESULTS:
        'Ceramics': 18, 'Math': 20, 'History': 5






        share|improve this answer



























          7














          You can use a dict to keep track of scores per name:



          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)


          RESULTS:
          'Ceramics': 18, 'Math': 20, 'History': 5






          share|improve this answer

























            7












            7








            7







            You can use a dict to keep track of scores per name:



            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)


            RESULTS:
            'Ceramics': 18, 'Math': 20, 'History': 5






            share|improve this answer













            You can use a dict to keep track of scores per name:



            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)


            RESULTS:
            'Ceramics': 18, 'Math': 20, 'History': 5







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 14 '18 at 0:21









            JacobIRRJacobIRR

            3,41521228




            3,41521228























                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


                then you can print it easy enough using format strings



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





                share|improve this answer



























                  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


                  then you can print it easy enough using format strings



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





                  share|improve this answer

























                    2












                    2








                    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


                    then you can print it easy enough using format strings



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





                    share|improve this answer













                    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


                    then you can print it easy enough using format strings



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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 14 '18 at 0:18









                    Joran BeasleyJoran Beasley

                    73k678118




                    73k678118





















                        0














                        Both the answers of @JacobIRR and @JoranBeasley are great, as alternative you could do the following:



                        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)


                        Output



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





                        share|improve this answer



























                          0














                          Both the answers of @JacobIRR and @JoranBeasley are great, as alternative you could do the following:



                          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)


                          Output



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





                          share|improve this answer

























                            0












                            0








                            0







                            Both the answers of @JacobIRR and @JoranBeasley are great, as alternative you could do the following:



                            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)


                            Output



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





                            share|improve this answer













                            Both the answers of @JacobIRR and @JoranBeasley are great, as alternative you could do the following:



                            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)


                            Output



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






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 14 '18 at 0:45









                            Daniel MesejoDaniel Mesejo

                            16.9k21430




                            16.9k21430



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291314%2ftrying-to-find-sums-of-unique-values-within-a-nested-dictionary-see-example%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                How to read a connectionString WITH PROVIDER in .NET Core?

                                Node.js Script on GitHub Pages or Amazon S3

                                Museum of Modern and Contemporary Art of Trento and Rovereto