Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save list of ordered tuples as CSV [duplicate]

Tags:

python

csv

tuples

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.

like image 829
Edmon Avatar asked Mar 22 '13 19:03

Edmon


People also ask

How do I save a tuple list to a CSV file?

You can convert a list of tuples to a CSV file by using NumPy's savetext() function and passing the NumPy array as an argument that arises from the conversion of the list of tuples.

How do I save a pandas list to a CSV file?

Using Pandas to_csv() function To convert the list to csv, we need to convert from list to dataframe and then use the to_csv() function to convert dataframe to a csv file. In this example, we have first imported pandas library and then define the four lists and map it with its column using a dictionary.

Is order preserved in tuple?

Tuple order is as you insert values into the tuple. They're not going to be sorted as I think you're asking. zip will again, retain the order you inserted the values in.


1 Answers

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 
like image 159
dawg Avatar answered Oct 23 '22 08:10

dawg