How do I return a new dictionary if the keys in one dictionary, match the keys in another dictionary?












12















Currently, I have a dictionary, with its key representing a zip code, and the values are also a dictionary.



d = { 94111: {'a': 5,  'b': 7,  'd': 7}, 
95413: {'a': 6, 'd': 4},
84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
73173: {'a': 15, 'c': 10, 'd': 15},
80132: {'b': 7, 'c': 7, 'd': 7} }


And then a second dictionary, which associates which state the zip code belongs to.



states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}


If the zip code in the dictionary states matches one of the keys in db then it would sum up those values and put it into a new dictionary like the expected output.



Expected Output:



{'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}




I've been stuck on how to proceed for almost an hour now and have absolutely no clue. So far this is the direction I am looking to go into but i'm not sure when both the keys match, how to create a dictionary that will look like the expected output.



def zips(d, states):
result = dict()
for key, value in db.items():
for keys, values in states.items():
if key == keys:


zips(d, states)









share|improve this question









New contributor




inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    12















    Currently, I have a dictionary, with its key representing a zip code, and the values are also a dictionary.



    d = { 94111: {'a': 5,  'b': 7,  'd': 7}, 
    95413: {'a': 6, 'd': 4},
    84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
    73173: {'a': 15, 'c': 10, 'd': 15},
    80132: {'b': 7, 'c': 7, 'd': 7} }


    And then a second dictionary, which associates which state the zip code belongs to.



    states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}


    If the zip code in the dictionary states matches one of the keys in db then it would sum up those values and put it into a new dictionary like the expected output.



    Expected Output:



    {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}




    I've been stuck on how to proceed for almost an hour now and have absolutely no clue. So far this is the direction I am looking to go into but i'm not sure when both the keys match, how to create a dictionary that will look like the expected output.



    def zips(d, states):
    result = dict()
    for key, value in db.items():
    for keys, values in states.items():
    if key == keys:


    zips(d, states)









    share|improve this question









    New contributor




    inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      12












      12








      12


      2






      Currently, I have a dictionary, with its key representing a zip code, and the values are also a dictionary.



      d = { 94111: {'a': 5,  'b': 7,  'd': 7}, 
      95413: {'a': 6, 'd': 4},
      84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
      73173: {'a': 15, 'c': 10, 'd': 15},
      80132: {'b': 7, 'c': 7, 'd': 7} }


      And then a second dictionary, which associates which state the zip code belongs to.



      states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}


      If the zip code in the dictionary states matches one of the keys in db then it would sum up those values and put it into a new dictionary like the expected output.



      Expected Output:



      {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}




      I've been stuck on how to proceed for almost an hour now and have absolutely no clue. So far this is the direction I am looking to go into but i'm not sure when both the keys match, how to create a dictionary that will look like the expected output.



      def zips(d, states):
      result = dict()
      for key, value in db.items():
      for keys, values in states.items():
      if key == keys:


      zips(d, states)









      share|improve this question









      New contributor




      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      Currently, I have a dictionary, with its key representing a zip code, and the values are also a dictionary.



      d = { 94111: {'a': 5,  'b': 7,  'd': 7}, 
      95413: {'a': 6, 'd': 4},
      84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
      73173: {'a': 15, 'c': 10, 'd': 15},
      80132: {'b': 7, 'c': 7, 'd': 7} }


      And then a second dictionary, which associates which state the zip code belongs to.



      states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}


      If the zip code in the dictionary states matches one of the keys in db then it would sum up those values and put it into a new dictionary like the expected output.



      Expected Output:



      {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}




      I've been stuck on how to proceed for almost an hour now and have absolutely no clue. So far this is the direction I am looking to go into but i'm not sure when both the keys match, how to create a dictionary that will look like the expected output.



      def zips(d, states):
      result = dict()
      for key, value in db.items():
      for keys, values in states.items():
      if key == keys:


      zips(d, states)






      python dictionary






      share|improve this question









      New contributor




      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited yesterday









      Georgy

      2,08341426




      2,08341426






      New contributor




      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked yesterday









      inspireinspire

      725




      725




      New contributor




      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      inspire is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          7 Answers
          7






          active

          oldest

          votes


















          11














          Using collections module



          Ex:



          from collections import defaultdict, Counter

          d = { 94111: {'a': 5, 'b': 7, 'd': 7},
          95413: {'a': 6, 'd': 4},
          84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
          73173: {'a': 15, 'c': 10, 'd': 15},
          80132: {'b': 7, 'c': 7, 'd': 7} }

          states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

          result = defaultdict(Counter)
          for k,v in d.items():
          if k in states:
          result[states[k]] += Counter(v)
          print(result)


          Output:



          defaultdict(<class 'collections.Counter'>, {'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7}), 
          'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10})})





          share|improve this answer
























          • I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

            – T.Lucas
            yesterday











          • Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

            – Swadhikar C
            yesterday











          • @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

            – Rakesh
            yesterday






          • 1





            @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

            – chepner
            yesterday



















          2














          You can just use defaultdict and count in a loop:



          expected_output = defaultdict(lambda: defaultdict(int))
          for postcode, state in states.items():
          for key, value in d.get(postcode, {}).items():
          expected_output[state][key] += value





          share|improve this answer
























          • What about defaultdict(Counter)?

            – Solomon Ucko
            yesterday



















          1














          Just as a complement of the answer of Rakesh, Here is an answer closer to your code:



          res = {v:{} for v in states.values()}

          for k,v in states.items():
          if k in d:
          sub_dict = d[k]
          output_dict = res[v]
          for sub_k,sub_v in sub_dict.items():
          output_dict[sub_k] = output_dict.get(sub_k, 0) + sub_v





          share|improve this answer































            1














            You can use something like this:



            d = { 94111: {'a': 5,  'b': 7,  'd': 7},                                                                                                                                                
            95413: {'a': 6, 'd': 4},
            84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
            73173: {'a': 15, 'c': 10, 'd': 15},
            80132: {'b': 7, 'c': 7, 'd': 7} }
            states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

            out = {i: 0 for i in states.values()}
            for key, value in d.items():
            if key in states:
            if not out[states[key]]:
            out[states[key]] = value
            else:
            for k, v in value.items():
            if k in out[states[key]]:
            out[states[key]][k] += v
            else:
            out[states[key]][k] = v
            # out -> {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





            share|improve this answer































              1














              You can use the class Counter for counting objects:



              from collections import Counter

              d = { 94111: {'a': 5, 'b': 7, 'd': 7},
              95413: {'a': 6, 'd': 4},
              84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
              73173: {'a': 15, 'c': 10, 'd': 15},
              80132: {'b': 7, 'c': 7, 'd': 7} }

              states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

              new_d = {}
              for k, v in d.items():
              if k in states:
              new_d.setdefault(states[k], Counter()).update(v)

              print(new_d)
              # {'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10}), 'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7})}


              You can convert new_d to the dictionary of dictionaries:



              for k, v in new_d.items():
              new_d[k] = dict(v)

              print(new_d)
              # {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





              share|improve this answer

































                1














                You can leverage dict's .items() method, which returns a list of tuples, and get the expected output in a simple one-liner:



                new_dict = {value:d[key] for key, value in states.items()}



                Output:



                {'AL': {'b': 7, 'c': 7, 'd': 7}, 'TX': {'a': 5, 'b': 15, 'c': 10, 'd': 11}}






                share|improve this answer































                  0














                  You might want to reconsider your choice of dict for how to store your data. If you store your data using pandas, aggregation is a lot easier.



                  df = pd.DataFrame(d).transpose()
                  df['states']=pd.Series(states)
                  df.groupby('states').sum()

                  >> a b c d
                  >>states
                  >>AL 21.0 7.0 17.0 26.0
                  >>TX 10.0 22.0 10.0 18.0





                  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
                    });


                    }
                    });






                    inspire is a new contributor. Be nice, and check out our Code of Conduct.










                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54459155%2fhow-do-i-return-a-new-dictionary-if-the-keys-in-one-dictionary-match-the-keys-i%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    7 Answers
                    7






                    active

                    oldest

                    votes








                    7 Answers
                    7






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    11














                    Using collections module



                    Ex:



                    from collections import defaultdict, Counter

                    d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                    95413: {'a': 6, 'd': 4},
                    84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                    73173: {'a': 15, 'c': 10, 'd': 15},
                    80132: {'b': 7, 'c': 7, 'd': 7} }

                    states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                    result = defaultdict(Counter)
                    for k,v in d.items():
                    if k in states:
                    result[states[k]] += Counter(v)
                    print(result)


                    Output:



                    defaultdict(<class 'collections.Counter'>, {'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7}), 
                    'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10})})





                    share|improve this answer
























                    • I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

                      – T.Lucas
                      yesterday











                    • Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

                      – Swadhikar C
                      yesterday











                    • @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

                      – Rakesh
                      yesterday






                    • 1





                      @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

                      – chepner
                      yesterday
















                    11














                    Using collections module



                    Ex:



                    from collections import defaultdict, Counter

                    d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                    95413: {'a': 6, 'd': 4},
                    84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                    73173: {'a': 15, 'c': 10, 'd': 15},
                    80132: {'b': 7, 'c': 7, 'd': 7} }

                    states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                    result = defaultdict(Counter)
                    for k,v in d.items():
                    if k in states:
                    result[states[k]] += Counter(v)
                    print(result)


                    Output:



                    defaultdict(<class 'collections.Counter'>, {'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7}), 
                    'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10})})





                    share|improve this answer
























                    • I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

                      – T.Lucas
                      yesterday











                    • Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

                      – Swadhikar C
                      yesterday











                    • @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

                      – Rakesh
                      yesterday






                    • 1





                      @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

                      – chepner
                      yesterday














                    11












                    11








                    11







                    Using collections module



                    Ex:



                    from collections import defaultdict, Counter

                    d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                    95413: {'a': 6, 'd': 4},
                    84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                    73173: {'a': 15, 'c': 10, 'd': 15},
                    80132: {'b': 7, 'c': 7, 'd': 7} }

                    states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                    result = defaultdict(Counter)
                    for k,v in d.items():
                    if k in states:
                    result[states[k]] += Counter(v)
                    print(result)


                    Output:



                    defaultdict(<class 'collections.Counter'>, {'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7}), 
                    'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10})})





                    share|improve this answer













                    Using collections module



                    Ex:



                    from collections import defaultdict, Counter

                    d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                    95413: {'a': 6, 'd': 4},
                    84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                    73173: {'a': 15, 'c': 10, 'd': 15},
                    80132: {'b': 7, 'c': 7, 'd': 7} }

                    states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                    result = defaultdict(Counter)
                    for k,v in d.items():
                    if k in states:
                    result[states[k]] += Counter(v)
                    print(result)


                    Output:



                    defaultdict(<class 'collections.Counter'>, {'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7}), 
                    'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10})})






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered yesterday









                    RakeshRakesh

                    38.5k124072




                    38.5k124072













                    • I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

                      – T.Lucas
                      yesterday











                    • Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

                      – Swadhikar C
                      yesterday











                    • @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

                      – Rakesh
                      yesterday






                    • 1





                      @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

                      – chepner
                      yesterday



















                    • I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

                      – T.Lucas
                      yesterday











                    • Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

                      – Swadhikar C
                      yesterday











                    • @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

                      – Rakesh
                      yesterday






                    • 1





                      @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

                      – chepner
                      yesterday

















                    I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

                    – T.Lucas
                    yesterday





                    I thought that using classes from collections was faster than bulit-in container but after testing it appears that your solution is slower, why ?

                    – T.Lucas
                    yesterday













                    Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

                    – Swadhikar C
                    yesterday





                    Hi @Rakesh, any specific reasons as to why you go with defaultdict rather than usual dict?

                    – Swadhikar C
                    yesterday













                    @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

                    – Rakesh
                    yesterday





                    @SwadhikarC..accelebrate.com/blog/using-defaultdict-python

                    – Rakesh
                    yesterday




                    1




                    1





                    @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

                    – chepner
                    yesterday





                    @T.Lucas Counter, at least, is a pure-Python, user-defined subclass of dict. There's no reason it would be faster than a dict alone.

                    – chepner
                    yesterday













                    2














                    You can just use defaultdict and count in a loop:



                    expected_output = defaultdict(lambda: defaultdict(int))
                    for postcode, state in states.items():
                    for key, value in d.get(postcode, {}).items():
                    expected_output[state][key] += value





                    share|improve this answer
























                    • What about defaultdict(Counter)?

                      – Solomon Ucko
                      yesterday
















                    2














                    You can just use defaultdict and count in a loop:



                    expected_output = defaultdict(lambda: defaultdict(int))
                    for postcode, state in states.items():
                    for key, value in d.get(postcode, {}).items():
                    expected_output[state][key] += value





                    share|improve this answer
























                    • What about defaultdict(Counter)?

                      – Solomon Ucko
                      yesterday














                    2












                    2








                    2







                    You can just use defaultdict and count in a loop:



                    expected_output = defaultdict(lambda: defaultdict(int))
                    for postcode, state in states.items():
                    for key, value in d.get(postcode, {}).items():
                    expected_output[state][key] += value





                    share|improve this answer













                    You can just use defaultdict and count in a loop:



                    expected_output = defaultdict(lambda: defaultdict(int))
                    for postcode, state in states.items():
                    for key, value in d.get(postcode, {}).items():
                    expected_output[state][key] += value






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered yesterday









                    tayfuntayfun

                    2,5221119




                    2,5221119













                    • What about defaultdict(Counter)?

                      – Solomon Ucko
                      yesterday



















                    • What about defaultdict(Counter)?

                      – Solomon Ucko
                      yesterday

















                    What about defaultdict(Counter)?

                    – Solomon Ucko
                    yesterday





                    What about defaultdict(Counter)?

                    – Solomon Ucko
                    yesterday











                    1














                    Just as a complement of the answer of Rakesh, Here is an answer closer to your code:



                    res = {v:{} for v in states.values()}

                    for k,v in states.items():
                    if k in d:
                    sub_dict = d[k]
                    output_dict = res[v]
                    for sub_k,sub_v in sub_dict.items():
                    output_dict[sub_k] = output_dict.get(sub_k, 0) + sub_v





                    share|improve this answer




























                      1














                      Just as a complement of the answer of Rakesh, Here is an answer closer to your code:



                      res = {v:{} for v in states.values()}

                      for k,v in states.items():
                      if k in d:
                      sub_dict = d[k]
                      output_dict = res[v]
                      for sub_k,sub_v in sub_dict.items():
                      output_dict[sub_k] = output_dict.get(sub_k, 0) + sub_v





                      share|improve this answer


























                        1












                        1








                        1







                        Just as a complement of the answer of Rakesh, Here is an answer closer to your code:



                        res = {v:{} for v in states.values()}

                        for k,v in states.items():
                        if k in d:
                        sub_dict = d[k]
                        output_dict = res[v]
                        for sub_k,sub_v in sub_dict.items():
                        output_dict[sub_k] = output_dict.get(sub_k, 0) + sub_v





                        share|improve this answer













                        Just as a complement of the answer of Rakesh, Here is an answer closer to your code:



                        res = {v:{} for v in states.values()}

                        for k,v in states.items():
                        if k in d:
                        sub_dict = d[k]
                        output_dict = res[v]
                        for sub_k,sub_v in sub_dict.items():
                        output_dict[sub_k] = output_dict.get(sub_k, 0) + sub_v






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered yesterday









                        T.LucasT.Lucas

                        5878




                        5878























                            1














                            You can use something like this:



                            d = { 94111: {'a': 5,  'b': 7,  'd': 7},                                                                                                                                                
                            95413: {'a': 6, 'd': 4},
                            84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                            73173: {'a': 15, 'c': 10, 'd': 15},
                            80132: {'b': 7, 'c': 7, 'd': 7} }
                            states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                            out = {i: 0 for i in states.values()}
                            for key, value in d.items():
                            if key in states:
                            if not out[states[key]]:
                            out[states[key]] = value
                            else:
                            for k, v in value.items():
                            if k in out[states[key]]:
                            out[states[key]][k] += v
                            else:
                            out[states[key]][k] = v
                            # out -> {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





                            share|improve this answer




























                              1














                              You can use something like this:



                              d = { 94111: {'a': 5,  'b': 7,  'd': 7},                                                                                                                                                
                              95413: {'a': 6, 'd': 4},
                              84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                              73173: {'a': 15, 'c': 10, 'd': 15},
                              80132: {'b': 7, 'c': 7, 'd': 7} }
                              states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                              out = {i: 0 for i in states.values()}
                              for key, value in d.items():
                              if key in states:
                              if not out[states[key]]:
                              out[states[key]] = value
                              else:
                              for k, v in value.items():
                              if k in out[states[key]]:
                              out[states[key]][k] += v
                              else:
                              out[states[key]][k] = v
                              # out -> {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





                              share|improve this answer


























                                1












                                1








                                1







                                You can use something like this:



                                d = { 94111: {'a': 5,  'b': 7,  'd': 7},                                                                                                                                                
                                95413: {'a': 6, 'd': 4},
                                84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                                73173: {'a': 15, 'c': 10, 'd': 15},
                                80132: {'b': 7, 'c': 7, 'd': 7} }
                                states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                                out = {i: 0 for i in states.values()}
                                for key, value in d.items():
                                if key in states:
                                if not out[states[key]]:
                                out[states[key]] = value
                                else:
                                for k, v in value.items():
                                if k in out[states[key]]:
                                out[states[key]][k] += v
                                else:
                                out[states[key]][k] = v
                                # out -> {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





                                share|improve this answer













                                You can use something like this:



                                d = { 94111: {'a': 5,  'b': 7,  'd': 7},                                                                                                                                                
                                95413: {'a': 6, 'd': 4},
                                84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                                73173: {'a': 15, 'c': 10, 'd': 15},
                                80132: {'b': 7, 'c': 7, 'd': 7} }
                                states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                                out = {i: 0 for i in states.values()}
                                for key, value in d.items():
                                if key in states:
                                if not out[states[key]]:
                                out[states[key]] = value
                                else:
                                for k, v in value.items():
                                if k in out[states[key]]:
                                out[states[key]][k] += v
                                else:
                                out[states[key]][k] = v
                                # out -> {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered yesterday









                                cmaureircmaureir

                                12914




                                12914























                                    1














                                    You can use the class Counter for counting objects:



                                    from collections import Counter

                                    d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                                    95413: {'a': 6, 'd': 4},
                                    84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                                    73173: {'a': 15, 'c': 10, 'd': 15},
                                    80132: {'b': 7, 'c': 7, 'd': 7} }

                                    states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                                    new_d = {}
                                    for k, v in d.items():
                                    if k in states:
                                    new_d.setdefault(states[k], Counter()).update(v)

                                    print(new_d)
                                    # {'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10}), 'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7})}


                                    You can convert new_d to the dictionary of dictionaries:



                                    for k, v in new_d.items():
                                    new_d[k] = dict(v)

                                    print(new_d)
                                    # {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





                                    share|improve this answer






























                                      1














                                      You can use the class Counter for counting objects:



                                      from collections import Counter

                                      d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                                      95413: {'a': 6, 'd': 4},
                                      84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                                      73173: {'a': 15, 'c': 10, 'd': 15},
                                      80132: {'b': 7, 'c': 7, 'd': 7} }

                                      states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                                      new_d = {}
                                      for k, v in d.items():
                                      if k in states:
                                      new_d.setdefault(states[k], Counter()).update(v)

                                      print(new_d)
                                      # {'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10}), 'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7})}


                                      You can convert new_d to the dictionary of dictionaries:



                                      for k, v in new_d.items():
                                      new_d[k] = dict(v)

                                      print(new_d)
                                      # {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





                                      share|improve this answer




























                                        1












                                        1








                                        1







                                        You can use the class Counter for counting objects:



                                        from collections import Counter

                                        d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                                        95413: {'a': 6, 'd': 4},
                                        84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                                        73173: {'a': 15, 'c': 10, 'd': 15},
                                        80132: {'b': 7, 'c': 7, 'd': 7} }

                                        states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                                        new_d = {}
                                        for k, v in d.items():
                                        if k in states:
                                        new_d.setdefault(states[k], Counter()).update(v)

                                        print(new_d)
                                        # {'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10}), 'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7})}


                                        You can convert new_d to the dictionary of dictionaries:



                                        for k, v in new_d.items():
                                        new_d[k] = dict(v)

                                        print(new_d)
                                        # {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}





                                        share|improve this answer















                                        You can use the class Counter for counting objects:



                                        from collections import Counter

                                        d = { 94111: {'a': 5, 'b': 7, 'd': 7},
                                        95413: {'a': 6, 'd': 4},
                                        84131: {'a': 5, 'b': 15, 'c': 10, 'd': 11},
                                        73173: {'a': 15, 'c': 10, 'd': 15},
                                        80132: {'b': 7, 'c': 7, 'd': 7} }

                                        states = {94111: "TX", 84131: "TX", 95413: "AL", 73173: "AL", 80132: "AL"}

                                        new_d = {}
                                        for k, v in d.items():
                                        if k in states:
                                        new_d.setdefault(states[k], Counter()).update(v)

                                        print(new_d)
                                        # {'TX': Counter({'b': 22, 'd': 18, 'a': 10, 'c': 10}), 'AL': Counter({'d': 26, 'a': 21, 'c': 17, 'b': 7})}


                                        You can convert new_d to the dictionary of dictionaries:



                                        for k, v in new_d.items():
                                        new_d[k] = dict(v)

                                        print(new_d)
                                        # {'TX': {'a': 10, 'b': 22, 'd': 18, 'c': 10}, 'AL': {'a': 21, 'd': 26, 'c': 17, 'b': 7}}






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited yesterday

























                                        answered yesterday









                                        Mykola ZotkoMykola Zotko

                                        165111




                                        165111























                                            1














                                            You can leverage dict's .items() method, which returns a list of tuples, and get the expected output in a simple one-liner:



                                            new_dict = {value:d[key] for key, value in states.items()}



                                            Output:



                                            {'AL': {'b': 7, 'c': 7, 'd': 7}, 'TX': {'a': 5, 'b': 15, 'c': 10, 'd': 11}}






                                            share|improve this answer




























                                              1














                                              You can leverage dict's .items() method, which returns a list of tuples, and get the expected output in a simple one-liner:



                                              new_dict = {value:d[key] for key, value in states.items()}



                                              Output:



                                              {'AL': {'b': 7, 'c': 7, 'd': 7}, 'TX': {'a': 5, 'b': 15, 'c': 10, 'd': 11}}






                                              share|improve this answer


























                                                1












                                                1








                                                1







                                                You can leverage dict's .items() method, which returns a list of tuples, and get the expected output in a simple one-liner:



                                                new_dict = {value:d[key] for key, value in states.items()}



                                                Output:



                                                {'AL': {'b': 7, 'c': 7, 'd': 7}, 'TX': {'a': 5, 'b': 15, 'c': 10, 'd': 11}}






                                                share|improve this answer













                                                You can leverage dict's .items() method, which returns a list of tuples, and get the expected output in a simple one-liner:



                                                new_dict = {value:d[key] for key, value in states.items()}



                                                Output:



                                                {'AL': {'b': 7, 'c': 7, 'd': 7}, 'TX': {'a': 5, 'b': 15, 'c': 10, 'd': 11}}







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered yesterday









                                                felipecgoncfelipecgonc

                                                565




                                                565























                                                    0














                                                    You might want to reconsider your choice of dict for how to store your data. If you store your data using pandas, aggregation is a lot easier.



                                                    df = pd.DataFrame(d).transpose()
                                                    df['states']=pd.Series(states)
                                                    df.groupby('states').sum()

                                                    >> a b c d
                                                    >>states
                                                    >>AL 21.0 7.0 17.0 26.0
                                                    >>TX 10.0 22.0 10.0 18.0





                                                    share|improve this answer




























                                                      0














                                                      You might want to reconsider your choice of dict for how to store your data. If you store your data using pandas, aggregation is a lot easier.



                                                      df = pd.DataFrame(d).transpose()
                                                      df['states']=pd.Series(states)
                                                      df.groupby('states').sum()

                                                      >> a b c d
                                                      >>states
                                                      >>AL 21.0 7.0 17.0 26.0
                                                      >>TX 10.0 22.0 10.0 18.0





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        You might want to reconsider your choice of dict for how to store your data. If you store your data using pandas, aggregation is a lot easier.



                                                        df = pd.DataFrame(d).transpose()
                                                        df['states']=pd.Series(states)
                                                        df.groupby('states').sum()

                                                        >> a b c d
                                                        >>states
                                                        >>AL 21.0 7.0 17.0 26.0
                                                        >>TX 10.0 22.0 10.0 18.0





                                                        share|improve this answer













                                                        You might want to reconsider your choice of dict for how to store your data. If you store your data using pandas, aggregation is a lot easier.



                                                        df = pd.DataFrame(d).transpose()
                                                        df['states']=pd.Series(states)
                                                        df.groupby('states').sum()

                                                        >> a b c d
                                                        >>states
                                                        >>AL 21.0 7.0 17.0 26.0
                                                        >>TX 10.0 22.0 10.0 18.0






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered yesterday









                                                        AcccumulationAcccumulation

                                                        1,39329




                                                        1,39329






















                                                            inspire is a new contributor. Be nice, and check out our Code of Conduct.










                                                            draft saved

                                                            draft discarded


















                                                            inspire is a new contributor. Be nice, and check out our Code of Conduct.













                                                            inspire is a new contributor. Be nice, and check out our Code of Conduct.












                                                            inspire is a new contributor. Be nice, and check out our Code of Conduct.
















                                                            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%2f54459155%2fhow-do-i-return-a-new-dictionary-if-the-keys-in-one-dictionary-match-the-keys-i%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







                                                            Popular posts from this blog

                                                            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                                            Alcedinidae

                                                            RAC Tourist Trophy