Skip to content Skip to sidebar Skip to footer

Yet Another List Csv File In Python Question

I have a file csv file in this format, I would like to generate the average for each step: elapsed,label 120,Step 01 260,Step 02 113,Step 03 100,Step 01 200,Step 02 103,Step 03 bu

Solution 1:

I believe this should achieve what you're attempting:

result= dict()
for file in sys.argv[1:]:
  forrowin csv.DictReader(open(file)):
    label =row['label']
    elapsed =float(row['elapsed'])
    if label inresult:
      result[label].append(elapsed)
    else:
      result[label] = [elapsed]

totals = dict((label, sum(values)) for label, valuesin result.iteritems())

After executing this, result will contain the lists in the format you wanted.

Solution 2:

If what you want is to make lists,

from collections import defaultdict
steps = defaultdict(list)

for file in sys.argv[1:]:
  forrowin csv.DictReader(open(file)):
    steps[row['label']].append(row['elapsed'])

averages = dict((key, sum(value)) for key, valuein steps.iteritems())

Will give you the averages.

What you're doing is attempting to add the string in row['elapsed'] to the string in label, but strings are immutable so can't be appended to. You can join them with string1 + string2 or `''.join((string1, string2)).

EDIT: Also, for your new error, See the last line of my code, or, try:

averages = {}
for item in result.iteritems():
    print item[0], sum(item[1])

Post a Comment for "Yet Another List Csv File In Python Question"