How to convert a list of dictionaries to CSV format in Python
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 …