Python Function to Save Array of Dictionaries to CSV
Here's a function that takes an array of dictionaries and saves it to a CSV file:
import csv
def save_dicts_to_csv(data, filename, fieldnames=None):
"""
Save an array of dictionaries to a CSV file.
Args:
data (list): List of dictionaries to save
filename (str): Name of the output CSV file
fieldnames (list, optional): List of fieldnames to use as headers.
If None, uses all keys from the first dict.
"""
if not data:
raise ValueError("No data provided to save")
# If fieldnames not provided, use all keys from the first dictionary
if fieldnames is None:
fieldnames = list(data[0].keys())
try:
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# Write header
writer.writeheader()
# Write data rows
writer.writerows(data)
print(f"Successfully saved data to {filename}")
except Exception as e:
print(f"Error saving to CSV: {e}")
raise
Usage Example
# Example data
data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Chicago"},
{"name": "Charlie", "age": 35, "city": "Los Angeles"}
]
# Save to CSV
save_dicts_to_csv(data, "output.csv")
Features
- Automatically detects field names from the first dictionary if not provided
- Handles UTF-8 encoding for international characters
- Includes error handling
- Uses proper CSV formatting with headers
- Works with Python's built-in
csv module (no external dependencies)
Customization Options
You can specify which fields to include by passing the fieldnames parameter:
# Only save name and city fields
save_dicts_to_csv(data, "output.csv", fieldnames=["name", "city"])
The function will raise a ValueError if the input data is empty.