Medium: Interview Core · Problem 51 of 82

Read Scores from CSV

MediumErrors and FilesPython

CSV text has a header line name,score followed by one row per student. Write read_scores(text) that returns a tuple (scores, bad_lines):

  • scores: a dictionary from name to score as an integer,
  • bad_lines: a list of the line numbers (first line is 1, the header counts) of rows that do not have exactly two fields or whose score is not an integer.

Blank lines are ignored (and are not bad). Names may be quoted and contain commas: "Smith, Jo",90.

Understand the problem

See why split(",") is not enough.

What does "\"Smith, Jo\",90".split(",") give?

  1. Two items: the name and the score
  2. Three items: the quoted name is cut at its comma
  3. One item

A plain split does not know about quotes, so the comma inside the name also splits. The result has three pieces and looks like a bad row. The csv module understands quoting.

How do you read CSV from a string instead of a file?

  1. csv.reader(text)
  2. csv.reader(io.StringIO(text))
  3. open(text)

csv.reader wants an iterable of lines. io.StringIO(text) makes a file-like object from a string: iterating over it gives the lines. This works the same as for a real file.

Write the solution

Return (scores, bad_lines).

def read_scores(text):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Which tool splits a CSV row correctly, and which attribute of it tells you the current line number?

Hint 2: the shape of the answer

reader = csv.reader(io.StringIO(text)); skip the header with next(reader, None). For each row, the line number is reader.line_num. An empty row is a blank line. Check len(row) == 2, then try int(row[1]).

Reflect

Solution

import csv
import io

def read_scores(text):
    scores = {}
    bad_lines = []
    reader = csv.reader(io.StringIO(text))
    next(reader, None)
    for row in reader:
        line = reader.line_num
        if not row:
            continue
        if len(row) != 2:
            bad_lines.append(line)
            continue
        try:
            scores[row[0]] = int(row[1])
        except ValueError:
            bad_lines.append(line)
    return scores, bad_lines

What this tests: the csv module, io.StringIO (a file made from a string), iterating a reader, next(it, default), and collecting errors instead of stopping at the first one.

Why the csv module: CSV has rules (quotes, commas inside quotes, quotes inside quotes, line breaks inside quotes). Hand-written splitting gets them wrong. Use the module for every CSV.

Collect, don't crash: real data has bad rows. Returning the good data plus a report of the bad lines is a design that lets the caller decide. (Another design raises an error on the first bad row; neither is wrong, but know which one you chose.)

DictReader reads rows as dictionaries keyed by the header, which is clearer when there are many columns.

What an interviewer might ask next: Read from a real file: with open(path, newline="") as f: and pass f to csv.reader. Why newline=""? (So the csv module sees the raw line endings and handles line breaks inside quotes correctly.)