Read a CSV File with csv.DictReader in Python

Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.

Easy Python 3.9+ Aug 9, 2026 Files & data 11 views 0 copies

Python code

28 lines
Python 3.9+
import csv
from pathlib import Path

def read_csv_with_dictreader(file_path):
    data = []
    with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data.append(row)
    return data

if __name__ == "__main__":
    # Create a sample CSV file for demonstration
    sample_file = Path('sample.csv')
    sample_file.write_text(
        'name,age,city\n'
        'Alice,30,New York\n'
        'Bob,25,Los Angeles\n'
        'Charlie,35,Chicago\n',
        encoding='utf-8'
    )
    
    rows = read_csv_with_dictreader(sample_file)
    for person in rows:
        print(f"{person['name']} is {person['age']} years old and lives in {person['city']}.")
    
    # Clean up sample file
    sample_file.unlink()

Output

stdout
Alice is 30 years old and lives in New York.
Bob is 25 years old and lives in Los Angeles.
Charlie is 35 years old and lives in Chicago.

How it works

csv.DictReader reads each row as an OrderedDict, using the first row as keys. Opening the file with newline='' prevents platform-specific newline translation issues. The encoding='utf-8' parameter ensures Unicode safety. Each row is appended to a list as a dictionary, allowing easy access by column name. The context manager ensures the file closes automatically.

Common mistakes

  • Forgetting `newline=''` when opening the file, which can cause extra blank lines.
  • Assuming all rows have the same keys without checking for missing data.
  • Not specifying `encoding='utf-8'`, leading to UnicodeDecodeError with non-ASCII characters.

Variations

  1. Use `with open(...) as f:` and `list(csv.DictReader(f))` for a one-liner.
  2. Read with `pandas.read_csv()` for built-in data analysis and transformation.

Real-world use cases

  • Importing user records from an exported spreadsheet into a web app database.
  • Reading batch configuration or metadata files in an ETL pipeline.
  • Loading revenue or sales data from daily CSV dumps for reporting dashboards.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.