How to convert a list of dictionaries to CSV format in Python
July 26, 2011 Comments
I was working on something last night where I needed to dump JSON data to a text file. I figured it might be a good idea to give an option to export it to a CSV file with headers as well so I wrote this simple function to do so:
import csv def export_dict_list_to_csv(data, filename): with open(filename, 'wb') as f: # Assuming that all dictionaries in the list have the same keys. headers = sorted([k for k, v in data[0].items()]) csv_data = [headers] for d in data: csv_data.append([d[h] for h in headers]) writer = csv.writer(f) writer.writerows(csv_data)
Tags: howto, python, tech, software development