Writing Defaultdict(list) To File
Previously asked a question Using defaultdict to parse multi delimiter file While I do get the desired output based on the code, I am struggling to write it to a file as a table in
Solution 1:
I would do this (python 2):
with open('mycsvfile.csv', 'wb') as f: # binary is better, avoids blank lines in some python 2 versions
writer = csv.writer(f,delimiter="\t")
keys=["count","pos","_pos","_neg"]
writer.writerow([""]+keys)
for k, vl in ids.iteritems():
for v in vl:
writer.writerow([k] + [v[key] for key in keys])
you need a double loop to iterate on the lists for each key. I have stored the column names in a list, so I can reuse it to build the rows in a list comprehension & for the title as well (first item doesn't have a title, I just left it blank)
now it looks like this:
count pos _pos _neg
31022550 0 20 0 0
31022550 2 20 2 0
31022550 0 20 0 0
(slightly shifted because tab character isn't wide enough, but not an issue to read it back)
Python 3 users would have to change:
withopen('mycsvfile.csv', 'wb') as f:
by
withopen('mycsvfile.csv', 'w',newline="") as f:
and
fork, vl in ids.iteritems():
by
for k, vl in ids.items(): # also works in python 2
note that the writerow
double loop could be replaced by a single line, a double-loop, flat generator comprehension passed to writerows
, faster to execute:
writer.writerows([k] + [v[key] forkeyin keys] fork, vl in ids.items() forvin vl)
Post a Comment for "Writing Defaultdict(list) To File"