Export List of Dicts to CSV in Python

Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.

Easy Python 3.9+ Aug 9, 2026 Files & data 14 views 0 copies

Python code

36 lines
Python 3.9+
import csv

def export_to_csv(data, filename):
    """Export a list of dicts to a CSV file."""
    if not data:
        print("No data to export")
        return
    
    # Get column names from the keys of the first dict
    fieldnames = list(data[0].keys())
    
    with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        
        # Write header row
        writer.writeheader()
        
        # Write data rows
        writer.writerows(data)
    
    print(f"Exported {len(data)} rows to {filename}")

if __name__ == "__main__":
    # Example data - list of dicts (dataframe-like structure)
    people = [
        {"name": "Alice", "age": 30, "city": "New York"},
        {"name": "Bob", "age": 25, "city": "Los Angeles"},
        {"name": "Charlie", "age": 35, "city": "Chicago"}
    ]
    
    export_to_csv(people, "people.csv")
    
    # Verify by reading back the file
    with open("people.csv", 'r') as f:
        print("\nCSV contents:")
        print(f.read())

Output

stdout
Exported 3 rows to people.csv

CSV contents:
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago

How it works

This script defines an export_to_csv function that takes a list of dictionaries and a filename. It extracts field names from the keys of the first dictionary to maintain consistent column order. Using csv.DictWriter with newline='' avoids extra blank lines on Windows, and encoding='utf-8' ensures proper handling of special characters. The writeheader() method writes the column names, and writerows() converts each dict to a CSV row automatically. Reading the file back with open() verifies the output.

Common mistakes

  • Assuming all dicts have the same keys; missing keys in later rows cause empty cells or errors.
  • Forgetting `newline=''` in `open()` which can produce extra blank lines between rows.
  • Using `csv.writer` instead of `csv.DictWriter` when dealing with dicts, requiring manual row construction.

Variations

  1. Use `pandas.DataFrame(data).to_csv(filename, index=False)` for more complex dataframe operations.
  2. Add a check that all dictionaries have the same set of keys before writing to avoid inconsistent data.

Real-world use cases

  • Exporting API query results (list of record objects) to a CSV for reporting or analytics.
  • Backing up user profile data from a database query into a downloadable spreadsheet format.
  • Creating compatibility files for external tools that expect CSV input from your application's data.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.