I have a .csv file laid out like this:
name1 name2 name3
value1 value2 value3
value4 value5 value6
value7 value8 value9
I need to find a way in Python3 to create a dictionary where the keys are the head names (name1, name2, name3) and the values are the sum of all the values underneath eg. name1 : (value1 + value4 + value7).
So far I've come up with:
def sumColumns(columnfile):
import csv
with open(columnfile) as csvfile:
rdr = csv.reader(csvfile)
output = {}
head = next(rdr)
total = 0
for column in head:
for row in rdr:
total += int(row[head.index(column)])
output[column] = total
total = 0
return output
I end up returning a dictionary with correct headers but something is going wrong with the sum that I can't pinpoint. One column gets summed and the rest are 0.
rdr
is an iterator. That means you can't re-iterate through it for each of the three timesfor row in rdr:
is called - only the first. I'll post a solution in a sec. – Alec