2

Merge two dictionaries of dictionaries

My question is similar to this one, but the answers don't produce the right result (for me?).

Take these dictionaries:

a = {'a': {'a': 1}}
b = {'a': {'b': 2}}

I want to produce:

c = {'a': {'a': 1, 'b': 2}}

Using the answers from the quoted question, these all produce:

c = a.copy()
c.update(b)

>>
c == {'a': {'b': 2}

Consider that a and b might be more complex than this, for example:

a = {'a': {'aa': {'aaa': 1}, 'bb': {'bbb': 2}}}
b = {'a': {'bb': {'aaa': 1}, 'bb': {'bbb': 2}}}
njminchin
  • 408
  • 3
  • 13

1 Answers1

1

In this case you can use

>>> a['a'].update(b['a'])
>>> a
{'a': {'a': 1, 'b': 2}}

Element in dictionary is also dictionary, so you can treat that element as dictionary. As for more complex example I don't know what result should be. But in general, you can access elements in element as dictionary in nested for loops.

Kaldesyvon
  • 86
  • 1
  • 8