arynhard
arynhard

Reputation: 542

Write csv with each list as column

I have a dictionary that holds a two level nested list for each key that looks like the following:

OrderedDict([(0,[['a','b','c','d'],['e','f','g','h']]), (1,[['i','j','k','l'],['m','n','o','p']])])

I would like to write each nested list to a csv as a column:

a,b,c,d      e,f,g,h
i,j,k,l      m,n,o,p

the output I am getting from my current code is:

['a','b','c','d']      ['e','f','g','h']
['i','j','k','l']      ['m','n','o','p']

The columns are correct but I would like to remove the brackets [ ] and quotes ' '

a,b,c,d      e,f,g,h
i,j,k,l      m,n,o,p

CODE:

with open('test.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, quotechar='"', quoting=csv.QUOTE_ALL)
    for record in my_dict.values():
        writer.writerow(record)

Any help would be appreciated!

Upvotes: 0

Views: 133

Answers (2)

KGo
KGo

Reputation: 20004

This should work:

with open('test.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, quotechar='"', quoting=csv.QUOTE_ALL)
    for record in my_dict.values():
        final = [",".join(index) for index in record]
        writer.writerow(final)

Upvotes: 1

erewok
erewok

Reputation: 7835

I am having trouble visualizing how your record looks because it seems like each value should be a nested list, meaning each column should contain both lists. If it were really writing one value from .values() at a time, it seems like you would get one column with both lists in it.

At any rate, what you want to achieve should probably be sought through the .join() method:

for record in my_dict.values():
    writer.writerow(','.join(record))

But the thing is, you're making a CSV (comma separated values) file, so each comma may be interpreted as a field-delimiter.

Question: Have you considered using a different delimiter when you instantiate your csv.writer?

Upvotes: 0

Related Questions