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

Turning a list of dictionaries into a single larger dictionary

Maybe this is a simple question, but I’ve been scratching my head on it.

How do I turn a list of several dictionaries into a single dictionary containing all values?

This is what I mean:

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

input_list = [
    {'fruit': 'banana',
     'color1': ''},
    {'vegetable': 'tomato',
     'color2': ''},
    {'dessert': 'ice cream',
     'taste': ''}
]

desired_output = {
    'fruit': 'banana',
    'color1': '',
    'vegetable': 'tomato',
    'color2': '',
    'dessert': 'ice cream',
    'taste': ''
}

Any help would be appreciated, thank you in advance.

>Solution :

Use this:

output = {key:value for element in input_list for key, value in element.items()}

Output:

{'fruit': 'banana',
 'color1': '',
 'vegetable': 'tomato',
 'color2': '',
 'dessert': 'ice cream',
 'taste': ''}
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