Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

group the values from different dictionary with same key

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading