0
0
Pythonprogramming~5 mins

Dictionary-based CSV handling in Python

Choose your learning style9 modes available
Introduction

Dictionary-based CSV handling lets you read and write CSV files using column names instead of numbers. This makes your code easier to understand and less error-prone.

When you want to read a CSV file and access data by column names like 'Name' or 'Age'.
When you want to write data to a CSV file and specify columns by their names.
When the order of columns in the CSV might change but you still want to access data correctly.
When you want clearer code that shows what each value means without guessing column positions.
Syntax
Python
import csv

# Reading CSV as dictionaries
with open('file.csv', mode='r', newline='') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['ColumnName'])

# Writing CSV from dictionaries
with open('file.csv', mode='w', newline='') as file:
    fieldnames = ['Column1', 'Column2']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Column1': 'Value1', 'Column2': 'Value2'})

DictReader reads each row as a dictionary with keys from the header row.

DictWriter writes dictionaries to CSV rows using specified fieldnames as columns.

Examples
This reads a CSV file named 'people.csv' and prints the 'Name' and 'Age' columns for each row.
Python
import csv

with open('people.csv', 'r', newline='') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row['Name'], row['Age'])
This writes two rows to 'people.csv' with columns 'Name' and 'Age'.
Python
import csv

fieldnames = ['Name', 'Age']
with open('people.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name': 'Alice', 'Age': '30'})
    writer.writerow({'Name': 'Bob', 'Age': '25'})
Sample Program

This program first writes two people's data to a CSV file using dictionary keys as columns. Then it reads the file back and prints a friendly sentence for each person using the column names.

Python
import csv

# Write sample data to CSV using DictWriter
fieldnames = ['Name', 'Age', 'City']
with open('sample.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'Name': 'John', 'Age': '28', 'City': 'New York'})
    writer.writerow({'Name': 'Emma', 'Age': '22', 'City': 'London'})

# Read the CSV back using DictReader
with open('sample.csv', 'r', newline='') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"{row['Name']} is {row['Age']} years old and lives in {row['City']}")
OutputSuccess
Important Notes

Always open CSV files with newline='' to avoid extra blank lines on some systems.

If a dictionary is missing a field when writing, that column will be empty in the CSV.

DictReader uses the first row of the CSV as keys automatically.

Summary

Dictionary-based CSV handling uses column names to read and write data.

It makes code easier to read and safer when column order changes.

Use csv.DictReader to read and csv.DictWriter to write CSV files with dictionaries.