Matic
Matic

Reputation: 17

Dictreader not working as expected

def sumColumns(filename):
    from csv import DictReader
    with open(filename) as f:
        a1=[row["bob"] for row in DictReader(f)] # I want this part to extract every
        a2=[row["anna"] for row in DictReader(f)]# column into a list and be put into
        a3=[row["tim"] for row in DictReader(f)] # variables. It only works for a1.
        dic={}
        total1=0
        total2=0
        total3=0
        for i in a1:
            total1 = total1 + float(i)
        dic["bob"] = total1 # adding the name of the person with the number into a dict
        for i in a2:
            total2 = total2 + float(i)
        dic["anna"] = total2
        for i in a3:
            total3 = total3 + float(i)
        dic["tim"] = total3
        return dic

My problem is that this code only works for the "a1" variable, the other 2 ones return 0 , so my final result is {'bob': 41.0, 'anna': 0, 'tim':0}.

I don't know how to fix this. Before this i tried the zip() function but that kept returning an error.

Here's the csv file for anyone that wants to download it :

http://tempsend.com/0D1ED483C3

And for anyone that doesn't like downloading files here's a picture of how it looks:

Image of csv file

Upvotes: 0

Views: 715

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

You are trying to re-read from the same file, but forgot to 'rewind' the file. Files have a current file position that is advanced when you read from a file; attempts to read after reaching the end then result in no data being read at all.

You could re-wind the file position to the start each time with f.seek(0), but rather than read from the file 3 times, you should read once and reuse the information:

with open(filename) as f:
    rows = list(DictReader(f))
    a1 = [row["bob"] for row in rows]
    a2 = [row["anna"] for row in rows]
    a3 = [row["tim"] for row in rows]

You could just use the sum() function here:

with open(filename) as f:
    rows = list(DictReader(f))
    dic['bob'] = sum(float(r['bob']) for r in rows)
    dic['anna'] = sum(float(r['anna']) for r in rows)
    dic['tim'] = sum(float(r['tim']) for r in rows)

or use a loop with names:

with open(filename) as f:
    rows = list(DictReader(f))
    for name in ('bob', 'anna', 'tim'):
        dic[name] = sum(float(r[name]) for r in rows)

Upvotes: 1

Related Questions