Skip to content

Instantly share code, notes, and snippets.

@mabroor
Created May 29, 2012 15:11
Show Gist options
  • Save mabroor/2828962 to your computer and use it in GitHub Desktop.
Save mabroor/2828962 to your computer and use it in GitHub Desktop.
How to convert a list of dicts to a CSV file
def dict2csv(dictlist, csvfile):
"""
Takes a list of dictionaries as input and outputs a CSV file.
"""
f = open(csvfile, 'wb')
fieldnames = dictlist[0].keys()
csvwriter = csv.DictWriter(f, delimiter=',', fieldnames=fieldnames)
csvwriter.writerow(dict((fn, fn) for fn in fieldnames))
for row in dictlist:
csvwriter.writerow(row)
fn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment