Python Dict List to Sum of ints -
so have series of lists i'd sum on , return each individual value of. lists this:
'testrel.txt': [1, 1, 1, 1, 1]
this recent traceback:
traceback (most recent call last): file "./seriescount.py", line 24, in <module> w.writerow(sum(series)) typeerror: unsupported operand type(s) +: 'int' , 'str'
i know why won't sum values (they're not integers , therefore can't summed), i'm having trouble syntax of casting list of key values ints. here's script:
#!/usr/bin/env python import csv import copy import os import sys import glob #get current working dir, set count, , select file delimiter os.chdir('/mypath') #parses through files , saves dict series = {} fn in glob.glob('*.txt'): open(fn) f: series[fn] = [1 line in f if line.strip() , not line.startswith('#')] print series #save dictionary key/val pairs csv open('seriescount.csv', 'wb') f: w = csv.dictwriter(f, series) w.writeheader() w.writerow(sum(series))
result should this:
'testrel.txt': 5
few issues in code -
when
sum(series)
, trying sum keys, not values. also, dictwriter's writerow expects dictionary input, not single value (whichsum()
return, if work @ all, wont anyway).you should not openning file (for writing csv in binary mode -
wb
) , open in write mode -w
.
instead of doing - sum(series)
- should try dictionary comprehension create sums of each key/value pair.
code -
with open('seriescount.csv', 'w') f: w = csv.dictwriter(f, series) w.writeheader() w.writerow({k:sum(v) k,v in series.items()})
demo -
>>> series = { ... 'mytext1.txt':[1,1,1,1,1,1], ... 'mytext2.txt':[1,1,1,1,1], ... 'mytext3.txt':[1,1,1,1,1,1,1,1,1,1,1,1]} >>> open('seriescount.csv', 'w') f: ... w = csv.dictwriter(f, series) ... w.writeheader() ... w.writerow({k:sum(v) k,v in series.items()}) ... 8
the result in seriescount.csv
-
mytext3.txt,mytext2.txt,mytext1.txt 12,5,6
Comments
Post a Comment