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.
Python code
36 linesimport 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
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
- Use `pandas.DataFrame(data).to_csv(filename, index=False)` for more complex dataframe operations.
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.