Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 6 · Lesson 3 · Core

CSV files and records

Read a CSV file with the csv module into a list of dictionaries and summarise it.

  • 50 minutes
  • Serves O4, O6
  • Assumes M6.L2

Phase 1: Prepare

Step 1 Warm-up recall

From M6.L2: what type is data read from a file?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • describe a CSV file (Foundation);
  • read rows as dictionaries (Core);
  • summarise a column (Core).

Phase 2: Teach

Step 3 A familiar example

A register has a header row naming the columns, then one row per student. Reading by column name is safer than by column number, because the order of columns can change.

Step 4 Clear explanation

A CSV file (comma-separated values) is a table written as text.

name,score0Ann,701Bo,852The header names the keys for each record
A CSV file is a table written as text: one record per line, fields separated by commas, the first line naming the columns.
import csv

rows = []
with open("scores.csv", newline="") as f:
    for row in csv.DictReader(f):
        rows.append(row)

total = 0
for r in rows:
    total = total + int(r["score"])
print(len(rows), total)
print(rows[0]["name"])
2 155
Ann

DictReader uses the first line as keys, so each row becomes a dictionary, and the file becomes a list of dictionaries as in Module 4. Values are still text, so convert them. The csv module also copes with commas inside quoted fields, which a plain split cannot.

The same care applies as before: the header must be exactly as written, and a field that has been changed by other software, such as a gene symbol turned into a date, will not match what you expect. Print the first and last rows after reading, to check what you really have.

Step 5 Worked example (4 marks)

A CSV has the header item,qty and the rows pen,3 and ink,2. Find rows[1]["item"] and the total qty.

  1. DictReader gives two dictionaries. (1 mark)
  2. rows[1] is the ink row, so item is ink. (1 mark)
  3. Total qty: 3 + 2 = 5. (1 mark)
  4. Answer: ink and 5. (1 mark)

Go deeper: the professor's notes

The format of stored data outlives the program, so choose complete and clear formats.
Year

Four digits.

Header

Named columns.

Unit

Written down.

Storeclear formatReadyears laterConvertcarefullyCheckfirst and last
Format

Choices

ChoiceRisk
two-digit yearconfusion after 1999
four-digit yearnone of that kind

At work: A date column

Dates arrive as text.

  1. Parse each date.
  2. Print the first and last.

What a careful practitioner decides. Store dates in a form that cannot be misread.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. DictReader takes its keys from:

2. Each row from DictReader is:

3. Values read from a CSV are:

4. CSV stands for:

Phase 4: Close

Step 7 Recap

  • CSV is a table in text form with a header line.
  • DictReader gives a list of dictionaries.
  • Convert fields and check the first and last rows.

Step 8 Exit ticket (ungraded)

Write the code that prints the name of every row with a score over 60.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that counts the rows for each value of a column called class.

In industry: Two digits for the year

To save memory, many old programs stored the year as two digits, so 1999 became 99. Estimates of the cost of fixing the Year 2000 problem ranged from about 100 billion US dollars in a 1999 Commerce Department figure to the 300 to 600 billion estimated by Gartner.

Link to this lesson. The way data is written in a file outlives the program that wrote it, so choose clear, complete formats.

Source: Network World (2009); US Senate special committee report, GPO (1999)

Common mistakes

MistakeWhy it fails
Treating fields as numbersConvert with int or float.
Wrong header spellingKeys must match exactly.
Opening without newline=""Use it with the csv module.

Limits. Very large files need other tools; this module uses small files that fit in memory.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · Why convert with int or float?
Text"70"int70Thenadd
Convert

Everything read from a file is text, so "70" + "85" gives "7085". Convert to numbers before adding or comparing.

Card 2 of 3 · What is a CSV file?
Lineone recordCommaseparatesHeadernames
CSV

A table written as text: one record per line, fields separated by commas, and a first line naming the columns. Most spreadsheets can save to it.

Card 3 of 3 · What does DictReader do?
HeaderkeysRowdictionaryUseby name
DictReader

It reads a CSV and gives each row as a dictionary, using the header as keys. You then write row["score"] instead of counting columns.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards