List of list of dictionaries to CSV

  • A+
Category:Languages

I know I can write a list of dictionaries directly to a CSV file. Similarly, is there a direct way to write a list of list of dictionaries to a csv file in python without iterating through each line manually?

Sample data

[[{'e': 46, 'p': 100, 'n': 0, 'a': 100, ...},    {'e': 29, 'p': 40, 'n': 1, 'a': 40, ...}, ...],  [{...}, ...] 

Expected format

e,p,n,a,.... 46,100,0,100,.... 29,40,1,40,... ....... 

Note this is not a list of dictionaries, but a list of list of dictionaries

 


Without Pandas, you can use itertools.chain to get a flattened list of all dictionaries and then write that to your CSV file with csv.DictWriter:

import csv from itertools import chain  data = [     [{'e': 46, 'p': 100, 'n': 0, 'a': 100},       {'e': 29, 'p': 40, 'n': 1, 'a': 40}],     [{'e': 56, 'p': 200, 'n': 23, 'a': 10},       {'e': 22, 'p': 41, 'n': 11, 'a': 420}]]  fieldnames = ['e', 'p', 'n', 'a'] with open('mydata.csv', 'w') as f:     writer = csv.DictWriter(f, fieldnames=fieldnames)     writer.writeheader()     writer.writerows(chain.from_iterable(data)) 

Output (mydata.csv)

e,p,n,a 46,100,0,100 29,40,1,40 56,200,23,10 22,41,11,420 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: