Python: Write Dict to CSV with Headers

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

Comments

Loading...