Home > database >  How to iterate over dictionaries in a list and extract key values to a separate list
How to iterate over dictionaries in a list and extract key values to a separate list

Time:11-29

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

CodePudding user response:

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.

  • Related