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 to iterate over dictionaries in a list and extract key values to a separate list

I’m trying to match key value from different dictionaries in a list and make them as individual list.Below is the example format

originallist=[
{"A":"Autonomous","C":"Combined","D":"Done"},
{"B":"Bars","A":"Aircraft"},
{"C":"Calculative"}
]
#Note: The dictionaries present in the original list may vary in number

#I was trying to acheive the below format

A=["Autonomous","Aircraft"]
B=["Bars"]
C=["Calculative","Combined"]
D=["Done"]

Thanks in advance for your help

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 :

The best option would be to use a defaultdict.

from collections import defaultdict

out = defaultdict(list)

#data is the list in question

for rec in data:
    for key,value in rec.items():
        out[key].append(value)

A defaultdict returns a default value in case the key does not exist. dict.items is a method that returns and iterator of the key value pairs.

You can do it faster using pandas, but it would be overkill unless you have a huge dataset.

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