In this lesson, you will learn how to make your CSV data more readable and manageable by automatically mapping rows to Python dictionaries using the csv module.
Moving Beyond Indices
When you read a CSV file using the basic csv.reader, each row is returned as a list of strings. If you want the "email" address, you have to remember its index—for example, row[2]. This is brittle; if someone adds a new column to the spreadsheet, your code breaks.
Python provides the csv.DictReader class to solve this. It treats the first row of your CSV as a header and maps every subsequent row into a dictionary where the keys are the header names.
Using DictReader and DictWriter
To use this, import the csv module and pass your file object to csv.DictReader. Here is how it looks in practice:
import csv
with open('employees.csv', mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
# Now you can access data by name!
print(f"Name: {row['name']}, Email: {row['email']}")
Similarly, if you want to write data back to a CSV, csv.DictWriter allows you to pass a dictionary directly to the writerow() method. You just need to specify the fieldnames so the writer knows which order to place the values in the file:
data = {'name': 'Alice', 'email': 'alice@example.com'}
with open('output.csv', mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['name', 'email'])
writer.writeheader()
writer.writerow(data)
Why This Matters
Using DictReader and DictWriter makes your code self-documenting. Instead of row[0], you use row['name']. This tells anyone reading your code exactly what data is being accessed. Furthermore, your scripts become resilient to changes in column order, as long as the header names remain consistent.
Key Takeaway: Use csv.DictReader and csv.DictWriter to map CSV data to dictionaries, allowing you to access fields by name rather than relying on error-prone numerical indices.