chrisaddy
chrisaddy

Reputation: 108

Merge values of list of dictionaries whose values are dictionaries

I have a list of dictionaries like

[
  {'a': {'q': 1}, 'b': {'r': 2}, 'c': {'s': 3}},
  {'a': {'t': 4}, 'b': {'u': 5}, 'c': {'v': 6}},
  {'a': {'w': 7}, 'b': {'x': 8}, 'c': {'z': 9}}
]

and I want the output to be

{
    'a': {'q': 1, 't': 4, 'w': 7},
    'b': {'r': 2, 'u': 5, 'x': 8},
    'c': {'s': 3, 'v': 6, 'z': 9}
}

Upvotes: 0

Views: 47

Answers (1)

sanyassh
sanyassh

Reputation: 8520

There are several ways of doing this, one with usage of collections.defaultdict:

import collections 

result = collections.defaultdict(dict)

lst = [
  {'a': {'q': 1}, 'b': {'r': 2}, 'c': {'s': 3}},
  {'a': {'t': 4}, 'b': {'u': 5}, 'c': {'v': 6}},
  {'a': {'w': 7}, 'b': {'x': 8}, 'c': {'z': 9}}
]

for dct in lst:
    for key, value in dct.items():
        result[key].update(value)

print(result)

Upvotes: 3

Related Questions