Data science: Read one column from CSV

Read a CSV table, including quoted fields, and print one of its columns.

What to build

A program that prints the values of a named column of a CSV table.

Requirements

  • Use the csv module so that quoted fields with commas or doubled quotes are read correctly.
  • If the column exists, print rows: R (the number of data rows) and then its values, one per line; otherwise print no column NAME.

Input

Line 1: the column name. Line 2: n, the number of CSV lines including the header. Then the n lines.

Output

The row count and the values, or the message.

Constraints

1 ≤ n ≤ 1000; fields contain no line breaks.

Example

Input:

city
4
name,city
Asha,Dhaka
"Lee, Jr.",Chattogram
Mina,Sylhet

Output:

rows: 3
Dhaka
Chattogram
Sylhet

Why it works

The csv module applies the quoting rules, so a name such as "Lee, Jr." stays one field, which splitting on commas would break into two.

Examples

Example 1 · Input
city
4
name,city
Asha,Dhaka
"Lee, Jr.",Chattogram
Mina,Sylhet
Expected output
rows: 3
Dhaka
Chattogram
Sylhet
Example 2 · Input
age
2
name,city
A,B
Expected output
no column age

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Collect the lines first, then pass the list to csv.reader.

Hint 2

header.index(name) gives the column's position.

Solution

Show one correct solution (try it yourself first)
import csv

name = input()
n = int(input())
lines = [input() for _ in range(n)]
rows = list(csv.reader(lines))
header, data = rows[0], rows[1:]
if name not in header:
    print("no column " + name)
else:
    i = header.index(name)
    print("rows:", len(data))
    for row in data:
        print(row[i])

Lesson: Reading CSV and JSON data →