1

I currently have a dictionary who values are lists.

Example: {1: [12, 13, 14, 15], 2: [12, 13, 14, 15], 3: [12, 13, 14, 15]} and so on.

I have 20000 keys, and each list contains 80 values.

I am trying to output this into a CSV file, but have had no luck using Dictwriter. Here is part of my code:

for i in range(0, 3):

    filetxt = "\\Level_3\\" + nonsbar[i]
    filedata = list(csv.reader(open(filetxt,'rb'), delimiter='\t'));

    for j in range (1, len(filedata)):
        tempid = filedata[j][0]
        idind = tempid.index('|')
        geneid = tempid[idind+1:len(tempid)]
        genecount = filedata[j][1]
        nconn[geneid].append(genecount)


for keys in nconn.keys():
    nconn[keys] = zip(nconn[keys])

print "convert to table"
nkeys = nconn.keys()
filetxt = open('nonsmoke.csv', 'wb')
nonsmoketab = csv.DictWriter(filetxt, nkeys,delimiter=',')
nonsmoketab.writeheader()
nonsmoketab.writerow(nconn)

I get an ouput like this:

114787  114786  
[('161.00',), ('985.00',), ('68.00',)]  [('9.00',), ('19.00',), ('2.00',)]

I instead want this:

114787 114786   
161     9
985     19
68      2

2 Answers 2

3

Do you want to transpose your dictionary of lists? You can do it with itertools.izip_longest for example:

from itertools import izip_longest
d = {1: [12, 13, 14, 15], 2: [16, 17, 18], 3: [19, 20, 21, 22]}
labels = d.keys()
rows = izip_longest(*d.values())

You can use csv.writer to serialize back to csv:

import StringIO
buf = StringIO.StringIO()
outf = csv.writer(buf)
outf.writerow(labels)
outf.writerows(rows)
print buf.getvalue()
# 1,2,3
# 12,16,19
# 13,17,20
# 14,18,21
# 15,,22
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This worked perfectly. Out of curiosity is there a more efficient way of handling all this data, I want to use python for some bayes-net, but I have to discretize the data first.
@user3131429 you should start a separate thread for a separate question, and describe it in full detail. At least this is free :) and welcomed as long as you're ontopic. Standard disclaimer, if you found answer useful and serving your needs, cosider accepting it.
0

I can give you a rough advise: implement from csv.DictWriter, overwrite method writerow(self, rowdict) and writerows(self, rowdicts), add loop on the result from self._dict_to_list(rowdict)(it's list in your case) in these 2 functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.