Last modified: Nov 10, 2024 By Alexander Williams

Python DictWriter: Write CSV Files Using Dictionary Format

The csv.DictWriter in Python provides an efficient way to write CSV files using dictionary-like objects. It's particularly useful when dealing with structured data that has consistent headers.

Understanding DictWriter Basics

While regular CSV writing works with lists, DictWriter allows you to work with dictionaries, making the code more readable and maintainable.

Here's a simple example of using DictWriter:


import csv

# Sample data
data = [
    {'name': 'John', 'age': 30, 'city': 'New York'},
    {'name': 'Alice', 'age': 25, 'city': 'Boston'}
]

# Writing to CSV
with open('people.csv', 'w', newline='') as file:
    fieldnames = ['name', 'age', 'city']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    
    writer.writeheader()  # Write the headers
    writer.writerows(data)  # Write all rows at once

The output file 'people.csv' will look like this:


name,age,city
John,30,New York
Alice,25,Boston

Key Features and Parameters

fieldnames is a required parameter that specifies the order and names of columns in the CSV file. It must match the dictionary keys you plan to write.

Writing Individual Rows

You can also write rows one at a time using writerow method:


import csv

with open('records.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['name', 'score'])
    writer.writeheader()
    
    # Writing individual rows
    writer.writerow({'name': 'Bob', 'score': 85})
    writer.writerow({'name': 'Emma', 'score': 92})

Handling Missing Keys

When dealing with incomplete data, DictWriter's restval and extrasaction parameters become useful:


import csv

data = [
    {'name': 'John', 'age': 30},  # Missing 'city'
    {'name': 'Alice', 'age': 25, 'city': 'Boston', 'country': 'USA'}  # Extra field
]

with open('partial_data.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, 
                          fieldnames=['name', 'age', 'city'],
                          restval='Unknown',
                          extrasaction='ignore')
    writer.writeheader()
    writer.writerows(data)

Integration with Other CSV Operations

DictWriter works well with csv.DictReader for reading and writing operations, and can be used in JSON to CSV conversions.

Error Handling

Always implement proper error handling when writing CSV files:


import csv

try:
    with open('output.csv', 'w', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=['name', 'age'])
        writer.writeheader()
        writer.writerow({'name': 'John', 'age': '30'})
except IOError:
    print("Error writing to CSV file")
except Exception as e:
    print(f"An error occurred: {str(e)}")

Conclusion

csv.DictWriter is a powerful tool for writing CSV files in Python. It simplifies the process of writing structured data and provides helpful features for handling missing or extra data.

Consider using DictWriter when you need to work with dictionary-based data or when you want to maintain clear column headers in your CSV files.