Home > OS >  How to write a list containing key and another list as value into CSV file per column in Python
How to write a list containing key and another list as value into CSV file per column in Python

Time:12-01

can someone please help me?

I have a list:

list = [('ac', [1, 1]), ('alex.miller', [1, 2]), ('blossom', [2, 3])]

I want to write it into CSV file to look like this:

ac,1,1

alex.miller,1,2

blossom,2,3

So far I tried (also tried to split the integer list, convert it to string and concatenate it back with row[0] but with no success, the output was like a,c,1,1 a,l,e,x,.,m etc.):

with open(r"user_statistics.csv", "a ") as csvfile_user:
  writer = csv.writer(csvfile_user)
  for row in list:
    writer.writerow(row)

But the output is:

ac,"[1, 1]"

alex.miller,"[1, 2]"

blossom,"[2, 3]"

How can I achieve this?

CodePudding user response:

You need to unpack the list with the values

writer.writerow((row[0], *row[1]))

Output:

ac,1,1

alex.miller,1,2

blossom,2,3

As a side note, don't use built in list as a variable name.

CodePudding user response:

You need to convert what you have into list of flat tuples or flat list before feeding into writerow, for example

my_list = [('ac', [1, 1]), ('alex.miller', [1, 2]), ('blossom', [2, 3])] 
my_list = [(i[0],*i[1]) for i in my_list]
print(my_list)

output

[('ac', 1, 1), ('alex.miller', 1, 2), ('blossom', 2, 3)]

Explanation: I used list comprehension and argument unpacking to convert tuples with str and list into flat tuples

As side note: do not use list as variable name, as it does overshadow built-in list.

CodePudding user response:

if using pandas is acceptable, then try this:

import pandas as pd
ls = [('ac', [1, 1]), ('alex.miller', [1, 2]), ('blossom', [2, 3])]

df = pd.DataFrame(ls, columns=['A', 'B'])

# split the list into new columns
df[['C','D']] = pd.DataFrame(df['B'].tolist(), index= df.index)

# drop that original list columns
df.drop('B', axis=1, inplace=True)
# finally convert to csv file
df.to_csv('mycsv.csv', index=False)
  • Related