Editor

Totals for Every Column

#605 · File handling · Intermediate · 70 XP · about 12 min

A CSV file stores a table as text: one row per line, with the cells separated by commas. In this file the first row is the header, the first column holds a label such as a name, and every other column holds whole numbers.

Write column_totals(filename) that reads the file with the csv module and returns a dictionary mapping each number column's header to the total of that column, in the order of the header. An empty cell counts as 0.

Example

If marks.csv holds:

name,math,science
Asha,80,72
Ben,65,90
"Lee, Ann",70,

then column_totals('marks.csv') returns {'math': 215, 'science': 162}. The quotes around "Lee, Ann" keep that comma inside one cell, which the csv module handles for you. Lee's science cell is empty, so it adds 0.

Constraints

  • The file has a header row and no blank lines.
  • At most 10,000 rows and 50 columns.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.