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

How do I combine several dictionaries with the same keys without losing any of values?

I have a list with several dicts:

l = [{'a': 'a1'}, {'c': 'c'}, {'a': 'a2'}, {'a': 'a3'}, {'y': 'y1'}, {'y': 'y4'}  etc]

and I want to combine them so that I’d get something like this:

l2 = [{'a': 'a1', 'a2', 'a3'}, {'c': 'c'}, {'y': 'y1', 'y4'}  etc]

How can I do this?

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

I tried to merge them but I ended up losing some of values every time.

>Solution :

Try this:

from collections import defaultdict

l = [{'a': 'a1'}, {'c': 'c'}, {'a': 'a2'}, {'a': 'a3'}, {'y': 'y1'}, {'y': 'y4'}]

merged_dict = defaultdict(list)

for d in l:
    for key, value in d.items():
        merged_dict[key].append(value)

result = [{key: values} for key, values in merged_dict.items()]

print(result)

OUTPUT

[{'a': ['a1', 'a2', 'a3']}, {'c': ['c']}, {'y': ['y1', 'y4']}]
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