I have a list of dictionaries:
x = [{'a': {'b': 'c'}}, {'a': {'d': 'e'}}]
I want the output [{'b': 'c', 'd': 'e'}] which is grouping of values if the keys are same from different dictionary. In the above example the key is ‘a’ and I want to get the values from all the keys with ‘a’.
>Solution :
Use a loop over the dictionaries and the keys, with dict.setdefault and dict.update as helper:
out = {}
for d in x:
for k, v in d.items():
out.setdefault(k, {}).update(v)
Output: {'a': {'b': 'c', 'd': 'e'}}
If you’re only interested in one key (e.g. "a"):
out = {}
for d in x:
out.update(d.get('a', {}))
# optional
# out = [out]
Alternatively:
from collections import ChainMap
out = dict(ChainMap(*(d['a'] for d in x if 'a' in d)))
Output: {'b': 'c', 'd': 'e'}