views:

123

answers:

2

I have a list of dictionaries that looks something like this:

toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]

What should I do to convert this to a csv file that looks something like this:

name,age,weight
bob,25,200
jim,31,180
+8  A: 
import csv
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
keys = ['name', 'age', 'weight']
f = open('people.csv', 'wb')
dict_writer = csv.DictWriter(f, keys)
dict_writer.writer.writerow(keys)
dict_writer.writerows(toCSV)

EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.

Matthew Flaschen
Thank you this works perfectly
bball
@bbal, if it worked perfectly, then accept it! Thanks are nice, but accepts are fundamental SO etiquette.
Alex Martelli
+7  A: 

In Python's csv module there is a DictWriter which will probably be helpful.

Wilduck