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.
Dictionary-based CSV handling in 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.
import csv with open('people.csv', 'r', newline='') as file: reader = csv.DictReader(file) for row in reader: print(row['Name'], row['Age'])
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'})
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.
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']}")
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.
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.