The Till Export

Working with CSV FilesMedium+20 XP+20

The Till Export

A chain of market stalls sends its sales to head office as raw CSV text — one long string, straight out of each stall's till. Before anyone can add anything up, that text has to be turned back into rows.

Task: write totals_by(text, key, value). It takes the CSV text, the name of a column to group by (key) and the name of a column of numbers to add up (value). It returns a dictionary mapping each key value to the total of its value column. The order of the keys doesn't matter.

How the text is laid out

  • Lines are separated by "\n", and the first line is always the header row of column names.
  • Every till writes its columns in its own order, so a column has to be found by its name, never by its position.
  • No value contains a comma. Values and column names can have stray spaces around them: " north " means north.

Tills are messy. Skip a line — quietly, without crashing — when:

  • it is blank (the text usually ends with "\n", which leaves an empty last line),
  • it has a different number of values from the header,
  • its key is empty, or its value is empty or the text NA.

Every other value is a valid number, possibly with a decimal point. Keys stay as text, even when they look like numbers.

Example

The NA line is skipped, and so is the empty line after the final "\n".

Examples

text = "stall,item,amount\nnorth,tea,2.5\nsouth,cake,3\nnorth,cake,3.25\nsouth,tea,NA\n"
key = "stall"
value = "amount"
returns {'north': 5.75, 'south': 3.0}
text = "amount, item ,stall\n 4.5,tea,east\n2,cake, west\n\n1.25, tea,east\n"
key = "item"
value = "amount"
returns {'tea': 5.75, 'cake': 2.0}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run