Read Scores from CSV
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?
- Two items: the name and the score
- Three items: the quoted name is cut at its comma
- 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?
csv.reader(text)csv.reader(io.StringIO(text))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.)
VISIBLE = 3
CASES = [
(('name,score\nAnn,90\nBob,x\nCy,70\n',), ({'Ann': 90, 'Cy': 70}, [3]), 'one bad row'),
(('name,score\n"Smith, Jo",85\n',), ({'Smith, Jo': 85}, []), 'a quoted name with a comma'),
(('name,score\n',), ({}, []), 'only the header'),
(('name,score\nAnn,90\n\nBob,80\n',), ({'Ann': 90, 'Bob': 80}, []), 'a blank line is ignored'),
(('name,score\nDan\nEve,1,2\n',), ({}, [2, 3]), 'wrong number of fields'),
(('name,score\nAnn,9.5\nBob,\n',), ({}, [2, 3]), 'scores that are not whole numbers'),
(('name,score\nAnn,90\nAnn,95\n',), ({'Ann': 95}, []), 'a repeated name: the last score wins'),
(('',), ({}, []), 'empty text'),
(('name,score\nAnn, 90\n',), ({'Ann': 90}, []), 'a space before the score'),
]