1

I am new to Python and this might've been answered already but I'm having trouble finding a similar question which would be dealing with merging multi-dictionary dictionaries.

So my question is: How can I merge dict1 and dict2 to end up with dict3 as shown below?

Thank you for your time and help!

#inputs
dict1 = {'aapl':
            {'Cash & Cash Equivalents':
                 {'2017': 74181,
                  '2016': 67155},
             'Receivables':
                 {'2017': 29299,
                  '2016': 30343}},
         'nvda':
            {'Cash & Cash Equivalents':
                 {'2017': 7108,
                  '2016': 6798},
             'Receivables':
                 {'2017': 826,
                  '2016': 505}}
         }

dict2 = {'aapl':
            {'Income Tax':
                 {'2017': 41181,
                  '2016': 12355},
             'After-Tax Income':
                 {'2017': 22323,
                  '2016': 12345}},
         'nvda':
            {'Income Tax':
                 {'2017': 1209,
                  '2016': 1192},
             'After-Tax Income':
                 {'2017': 12326,
                  '2016': 11093}}
         }

#output
dict3 = {'aapl':
            {'Cash & Cash Equivalents':
                 {'2017': 74181,
                  '2016': 67155},
             'Receivables':
                 {'2017': 29299,
                  '2016': 30343},
             'Income Tax':
                 {'2017': 41181,
                  '2016': 12355},
             'After-Tax Income':
                 {'2017': 22323,
                  '2016': 12345}},
         'nvda':
            {'Cash & Cash Equivalents':
                 {'2017': 7108,
                  '2016': 6798},
             'Receivables':
                 {'2017': 826,
                  '2016': 505},
             'Income Tax':
                 {'2017': 1209,
                  '2016': 1192},
             'After-Tax Income':
                 {'2017': 12326,
                  '2016': 11093}}
         }
michael0196
  • 1,497
  • 1
  • 9
  • 21
  • 1
    You could do `for k in dict1: dict1[k].update(dict2[k])` but that would change `dict1` and it assumes that all of the keys in `dict1` are in `dict2` – pault Feb 22 '18 at 17:21
  • 1
    Should I delete the question? It's very much the same, except my first two keys are different from the example in Dictionaries of dictionaries merge? – michael0196 Feb 22 '18 at 17:30

0 Answers0