typestar

CSV with dictionaries in Python

Reading and writing CSV rows as dicts.

import csv
import io

raw = "name,score\nada,95\ngrace,88\nkatherine,92\n"

reader = csv.DictReader(io.StringIO(raw))
rows = list(reader)
top = max(rows, key=lambda r: int(r["score"]))

out = io.StringIO()
writer = csv.DictWriter(out, fieldnames=["name", "score"])
writer.writeheader()
writer.writerows(rows)
text = out.getvalue()

How it works

  1. DictReader yields each row keyed by header.
  2. max with a key finds the top row.
  3. DictWriter writes the header and rows back out.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
330
Tokens
101
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 2 of 5 in Data formats, step 18 of 41 in Domain tools.

← Previous Next →