brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's csv.DictReader gives you each row as a dict keyed by the header

Python
~/tips/tip-python-csv-dictreader

import csv

Read CSV files by column name instead of counting column positions.

Spreadsheet exports break scripts as soon as someone adds or moves a column. I prefer reading CSV files with csv.DictReader, so you can use the column names instead of positions.

import csv

with open("export.csv", newline="", encoding="utf-8-sig") as f:
    for row in csv.DictReader(f):
        print(row["email"], row["plan"])

The first line of the file becomes the keys, and every following row is a dict. If a column moves from position 3 to position 5, row["email"] still finds it.

Two details in that open() call are there on purpose. newline="" is what the docs ask for, so quoted fields with line breaks inside them are read correctly. And utf-8-sig quietly removes the invisible byte order mark that Excel likes to put at the start of a file. Without it, your first column is called "\ufeffemail" and the lookup fails with a KeyError that makes no sense until you print the keys.

Every value comes back as a string, including numbers and empty cells. Convert with int() or float() where you need maths. For writing, csv.DictWriter is the mirror image: give it fieldnames, call writeheader() once and then writerow() with dicts.

Further reading: csv.DictReader

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link