Wednesday, September 4, 2013

Python - Write dictionary data to csv file

Assuming I have a list of dictionaries called mydict:

mydict = [{'name': 'Trinh Nguyen', 'value': 'Super Genius'}, {'name':'God', 'value': 'Cool'},...]



and I want to write that list to a csv file, so I write the following reusable python function:

import csv

def write_dict_data_to_csv_file(csv_file_path, dict_data):
    csv_file = open(csv_file_path, 'wb')
    writer = csv.writer(csv_file, dialect='excel')
   
    headers = dict_data[0].keys()
    writer.writerow(headers)

    for dat in dict_data:
        line = []
        for field in headers:
            line.append(dat[field])
        writer.writerow(line)
       
    csv_file.close()


write_dict_data_to_csv_file('mycsv.csv', mydict)