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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












18















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


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




























    18















    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


    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


























      18












      18








      18


      3






      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


      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
















      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


      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















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 2 at 11:11









      halfer

      14.6k758112




      14.6k758112










      asked Jan 31 at 11:04









      inspireinspire

      995




      995






















          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
            Jan 31 at 11:46











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

            – Swadhikar C
            Jan 31 at 12:20











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

            – Rakesh
            Jan 31 at 12:29






          • 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
            Jan 31 at 20:42


















          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
            Jan 31 at 22:07


















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



                    );













                    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
                      Jan 31 at 11:46











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

                      – Swadhikar C
                      Jan 31 at 12:20











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

                      – Rakesh
                      Jan 31 at 12:29






                    • 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
                      Jan 31 at 20:42















                    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
                      Jan 31 at 11:46











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

                      – Swadhikar C
                      Jan 31 at 12:20











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

                      – Rakesh
                      Jan 31 at 12:29






                    • 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
                      Jan 31 at 20:42













                    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 Jan 31 at 11:10









                    RakeshRakesh

                    39.3k124072




                    39.3k124072












                    • 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
                      Jan 31 at 11:46











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

                      – Swadhikar C
                      Jan 31 at 12:20











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

                      – Rakesh
                      Jan 31 at 12:29






                    • 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
                      Jan 31 at 20:42

















                    • 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
                      Jan 31 at 11:46











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

                      – Swadhikar C
                      Jan 31 at 12:20











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

                      – Rakesh
                      Jan 31 at 12:29






                    • 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
                      Jan 31 at 20:42
















                    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
                    Jan 31 at 11:46





                    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
                    Jan 31 at 11:46













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

                    – Swadhikar C
                    Jan 31 at 12:20





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

                    – Swadhikar C
                    Jan 31 at 12:20













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

                    – Rakesh
                    Jan 31 at 12:29





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

                    – Rakesh
                    Jan 31 at 12:29




                    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
                    Jan 31 at 20:42





                    @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
                    Jan 31 at 20:42













                    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
                      Jan 31 at 22:07















                    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
                      Jan 31 at 22:07













                    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 Jan 31 at 11:17









                    tayfuntayfun

                    2,5301119




                    2,5301119












                    • What about defaultdict(Counter)?

                      – Solomon Ucko
                      Jan 31 at 22:07

















                    • What about defaultdict(Counter)?

                      – Solomon Ucko
                      Jan 31 at 22:07
















                    What about defaultdict(Counter)?

                    – Solomon Ucko
                    Jan 31 at 22:07





                    What about defaultdict(Counter)?

                    – Solomon Ucko
                    Jan 31 at 22:07











                    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 Jan 31 at 11:17









                        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 Jan 31 at 11:17









                                cmaureircmaureir

                                18215




                                18215





















                                    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 Jan 31 at 14:23

























                                        answered Jan 31 at 11:19









                                        Mykola ZotkoMykola Zotko

                                        785215




                                        785215





















                                            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 Jan 31 at 19:14









                                                felipecgoncfelipecgonc

                                                966




                                                966





















                                                    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 Jan 31 at 19:43









                                                        AcccumulationAcccumulation

                                                        1,39329




                                                        1,39329



























                                                            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%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

                                                            How to check contact read email or not when send email to Individual?

                                                            Bahrain

                                                            Postfix configuration issue with fips on centos 7; mailgun relay