简体   繁体   中英

How to export a nested dictionary into a csv and format it into columns and rows?

I tried to search for my problem, but I couldn't find anything closley related, so I decided to put my question in here. I'm pretty new to Python and still learning this languange, so forgive me if I didn't catch obvious things.

Currently I'm trying to extract data via beautifulsoup from some letters that were transformed into .xml-files. Those extracted data - I put them into a nested dictionary. What I want to accomplish is a csv-file which contains all those data.

I've got a nested dictionary like this:

dict = [
 {"id":"0", "foundPersons" : ["Smith, Bernhard","Jackson, Andrew","Dalton, Henry"], "sendfrom" : "Calahan, Agnes"}, 
 {"id":"1", "foundPersons" : ["Cutter, John","Ryan, Jack"], "sendfrom" : "Enrico, Giovanni"}
 {"id":"2", "foundPersons" : "Grady, Horace", "sendfrom" : "Calahan, Agnes"}
]

I want to have ID, foundPersons and sendfrom als the header of each column. Then below the ID header I want to have every ID in each cell, every foundPerson of one ID into one cell (that means that those 3 names of ID0 are in one cell) and so on.

I tried that by using the csv module but I couldn't figure out how to accomplish that. Can somebody maybe give me a hint? Or is there any other module / library which can help me out here?

You want to use the pandas library here.

import pandas as pd

data = pd.DataFrame.from_dict(dict)
data.to_csv('output.csv')

print(data)

And your data is now organized to columns and rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM