Standard Library
CSV Data
DictReader uses the header row as dictionary keys. The values are still strings because CSV is text.
Source
import csv
import io
text = "name,score\nAda,98\nGrace,95\n"
rows = list(csv.DictReader(io.StringIO(text)))
print(rows[0])
print(type(rows[0]["score"]).__name__)Output
{'name': 'Ada', 'score': '98'}
strConvert numeric fields at the boundary where the program leaves CSV text and starts doing arithmetic.
Source
print(sum(int(row["score"]) for row in rows))Output
193DictWriter turns dictionaries back into row-shaped text with the same column order.
Source
output = io.StringIO(newline="")
writer = csv.DictWriter(output, fieldnames=["name", "passed"])
writer.writeheader()
writer.writerow({"name": "Ada", "passed": True})
print(output.getvalue().splitlines()[1])Output
Ada,TrueNotes
- Let
csvhandle quoting and delimiters instead of callingsplit(","). - CSV fields are text until your code converts them.
- Reach for JSON when records need nested lists, dictionaries, booleans, or numbers that preserve their type.
See also
- prerequisite: Strings
- prerequisite: Dictionaries
- related: JSON
Run the complete example
Expected output
{'name': 'Ada', 'score': '98'}
193
Ada,True
Execution time appears here after you run the example.