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
DictReaderyields each row keyed by header.maxwith a key finds the top row.DictWriterwrites the header and rows back out.
Keywords and builtins used here
intlambdalistmax
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.
Step 2 of 5 in Data formats, step 18 of 41 in Domain tools.