Python: Write Dict to CSV with Headers
Author:CodeSnippets
Language:
Python
6 views
0 favorites
2 hours ago
Code Implementation
Python
import csv
def write_dict_to_csv(file_path, data):
with open(file_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
# Usage
rows = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
write_dict_to_csv("output.csv", rows)
Write a list of dictionaries to a CSV file and automatically generate headers.
#dict#csv
Snippet Description
- Input must be a list of dictionaries
fieldnames
automatically uses the keys from the first record- Can be used to export data reports
Recommended Snippets
Python Read Nested JSON File Example
How to read JSON files with nested structures in Python and safely access deep-level fields.
Python
#json+1
8
0
Python read JSON from file example
The simplest code snippet for reading a JSON file using Python, implemented with the built-in json module.
Python
#json
12
0
Python Remove Duplicates from List of Dicts
Remove duplicates from a list of dictionaries based on a specific key in the dictionaries.
Python
#dict+1
6
0
Comments
Loading...