Save list of ordered tuples as CSV

Question:

I have a list of tuples ordered by value. They are in the form (name,count) where
count is number of occurrences for each unique name.

I would like to take this list and transform it into CSV where each name is column header
and each value is column value of a single row.

Any suggestions how to do it? Thanks.

Asked By: Edmon

||

Answers:

Python, transposing a list and writing to a CSV file

import csv   
lol = [(1,2,3),(4,5,6),(7,8,9)]
item_length = len(lol[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in lol])

output

1,4,7
2,5,8
3,6,9

Note that trying it in python 3 might give the error as mentioned in TypeError: a bytes-like object is required, not ‘str’ in python and CSV.

Consider to use with open('ur file.csv','w') as out: for python 3.

Answered By: 0x90

You can do this:

import csv

# note: If you use 'b' for the mode, you will get a TypeError
# under Python3. You can just use 'w' for Python 3

data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]

with open('ur file.csv','wb') as out:
    csv_out=csv.writer(out)
    csv_out.writerow(['name','num'])
    for row in data:
        csv_out.writerow(row)

    # You can also do csv_out.writerows(data) instead of the for loop

the output file will have:

name,num
"smith, bob",2
carol,3
ted,4
alice,5
Answered By: dawg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.