Converting list of lists into tuple and write to csv

Question:

I have a list of lists.

lst = [['cp1', 'cp2'], ['ac1', 'ac2'], ['12/12/2020', '12/12/2020']]

i want to convert this into dict or tuple and write to csv as per below format.

cp1;ac1;12/12/2020

cp2,ac2,12/12/2020

but the length of lst is not fixed it is dynamic (here it is 3 lists inside but can it can be N) . However lists in lst will have same number of element (in above example length is 2 ) .

Any pointer will be helpfull .

Asked By: Akash Tripathi

||

Answers:

You can use the zip builtin:

>>> list(zip(*lst))
[('cp1', 'ac1', '12/12/2020'), ('cp2', 'ac2', '12/12/2020')]

This will work with lists of any size.

Answered By: Selcuk

I think this is the code you need:

lst = [['cp1', 'cp2'], ['ac1', 'ac2'], ['12/12/2020', '12/12/2020']]
output = ""
for inner_list in lst:
    output += inner_list[0] + ";"
output = output[:len(output) - 2] + "nn"
for inner_list in lst:
    output += inner_list[1] + ";"
output = output[:len(output) - 2]
print(output)
Answered By: Cohen

Use zip and csv module:

data  = [['cp1', 'cp2'], ['ac1', 'ac2'], ['12/12/2020', '12/12/2020']]

import csv

with open ("test.csv","w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(zip(*data))


with open("test.csv") as r:
    print(r.read())

Output:

cp1,ac1,12/12/2020
cp2,ac2,12/12/2020

This will work as long as you make sure your inner lists all have the same lenght. If one is shorter all lists will be shortened to that lenght. Use itertools.zip_longest to avoid that shortening.

See Writing a Python list of lists to a csv file if your lists are already formatted correctly and do not need to be transposed before writing.

Answered By: Patrick Artner
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.