Course contentsShow
← Python
Lesson 735 of 1,06011. Standard Library EssentialsFree lesson

Handling CSV Files with Dictionary Mapping

Leverage DictReader and DictWriter to map CSV columns directly to Python dictionaries, improving code readability and data accessibility.

In this lesson, you will learn how to improve the readability and accessibility of your tabular data by mapping CSV columns directly to Python dictionaries using DictReader and DictWriter.

When you read a standard CSV file using the basic csv.reader, you get back a list of strings. Accessing data requires remembering column indexes (e.g., row[0]), which is error-prone and makes your code hard to read if the column order changes. Using csv.DictReader solves this by turning each row into a dictionary where the keys are the column headers.

Reading with DictReader

Instead of working with lists, DictReader maps your data so you can access values by their specific header name.

import csv

with open('employees.csv', mode='r', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        # Access data by column name instead of index
        print(f"Name: {row['name']}, Department: {row['dept']}")

Writing with DictWriter

Similarly, csv.DictWriter allows you to write dictionaries back into a CSV file. This is highly beneficial because it ensures that your data is written in the correct order based on a predefined list of fieldnames, regardless of the order of keys in your Python dictionary.

import csv

data = [{'name': 'Alice', 'dept': 'HR'}, {'name': 'Bob', 'dept': 'IT'}]
fields = ['name', 'dept']

with open('output.csv', mode='w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=fields)
    writer.writeheader()  # Writes the top row based on fieldnames
    writer.writerows(data) # Writes the dictionary values

By using these dictionary-based readers and writers, your code becomes self-documenting. If a new column is added to your CSV file, your logic remains intact because you are explicitly calling the key name (row['name']) rather than relying on a fragile index (row[0]). This approach creates a cleaner, more robust bridge between raw file storage and your Python application logic.

Key Takeaway: Use DictReader and DictWriter to replace magic-number indexes with descriptive column keys, making your CSV processing code significantly more readable and maintainable.