CSV and JSON files · 2 / 15 Theory

DictReader and DictWriter

Accessing columns by position (row[2]) is awkward and error-prone: if you add a column, all the numbers change. DictReader and DictWriter work with dictionaries, using the header as keys.

DictReader: each row is a dictionary

import csv

lines = [
    "name,age,city",
    "Ana,30,Madrid",
    "Luis,25,Lyon",
]

for row in csv.DictReader(lines):
    print(row)
# {'name': 'Ana', 'age': '30', 'city': 'Madrid'}
# {'name': 'Luis', 'age': '25', 'city': 'Lyon'}

DictReader reads the first line as a header automatically. Now you can access by the column name:

for row in csv.DictReader(lines):
    print(row["name"], row["city"])
# Ana Madrid
# Luis Lyon

If you ask for a column that does not exist, you get a KeyError, so check that the names match the header exactly (also upper and lower case).

Filtering and calculating

lines = [
    "name,age,city",
    "Ana,30,Madrid",
    "Luis,25,Lyon",
    "Eva,41,Madrid",
]

from_madrid = []
total_age = 0
for row in csv.DictReader(lines):
    total_age += int(row["age"])
    if row["city"] == "Madrid":
        from_madrid.append(row["name"])

print(from_madrid)      # ['Ana', 'Eva']
print(total_age / 3)    # 32.0

Reading a file with DictReader

with open("people.csv", "r", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])

Since each row is a dictionary, you can also store them in a list and work with it afterwards:

with open("people.csv", "r", newline="", encoding="utf-8") as f:
    people = list(csv.DictReader(f))

print(len(people))

DictWriter: writing dictionaries

DictWriter needs the list of columns (fieldnames). writeheader() writes the header and writerow each dictionary:

import io

people = [
    {"name": "Ana", "age": 30},
    {"name": "Pérez, Luis", "age": 25},
]

output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["name", "age"], lineterminator="\n")
writer.writeheader()
writer.writerows(people)

print(output.getvalue())
# name,age
# Ana,30
# "Pérez, Luis",25

reader or DictReader

csv.readercsv.DictReader
Each row isa lista dictionary
Access to a columnrow[1]row["age"]
Headerhas to be skipped with nextused automatically as keys
Use it whenthere is no headerthere is a header (the most common)

Practice in Filter rows by city and From CSV to JSON.