0

I have a list of dictionaries, some of which share the same key at levels 1 and 2, some share the same key just a level 1, some don't share a key. I want to merge the dictionaries together starting from the top level.

input = [
d1 = {'a' : {'az' : {'a1': 2}}}
d2 = {'a' : {'az' : {'g' : 9}}}
d3 = {'a' : {'aa' : {'g' : 9}}}
d4 = {'b' : {'az' : {'g' : 9}}}
]

result = [
{'a': {'az' : {'a1' : 2, 'g' : 9}, {'aa' : {'g' : 9}}}
{'b' : {'az' : {'g' : 9}}}
]
Mattreex
  • 189
  • 2
  • 17

1 Answers1

2

The easiest approach would be to recursively merge the dictionaries, see sample below.

# https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
def merge(A, B):
    for k, v in B.items():
        if k in A and isinstance(A[k], dict) and isinstance(v, dict):
            merge(A[k], v)
        else:
            A[k] = v

input_dicts = [
    {'a' : {'az' : {'a1': 2}}},
    {'a' : {'az' : {'g' : 9}}},
    {'a' : {'aa' : {'g' : 9}}},
    {'b' : {'az' : {'g' : 9}}}
]

result = {}
for d in input_dicts:
    merge(result, d)
CMMCD
  • 360
  • 1
  • 8