List indexing writing on the csv file as an output

List indexing writing on the csv file as an output
0
#1

I reach a below list after calculation in my code.

list= [‘danial’, 5104, ‘peter’, 9770]

now my question is how can I write it on csv file like below:

danial,5104
peter,9770

#2

I would start by re-grouping that list. Pair the ‘name’ and ‘number’ items somehow (tuple, dictionary, etc…). Then simply import the csv module and iterate through your list of paired items to write them to a row. I can’t really give a better method without seeing the full structure of the list you need to write. If all the items in the list follow your example code:

import csv

example = ['danial', 5104, 'peter', 9770]
paired_example = [(x, example[i+1]) for i, x in enumerate(example) if type(x) is str]
# paired_example = [(danial, 5104), (peter, 9770)]

with open("example.csv", "w") as file:
    writer = csv.writer(file, delimiter=",")
    for item in paired_example:
        writer.writerow(item)

Alternatively you could also use the csv modules DictWriter class instead for this:

import csv

example = ['danial', 5104, 'peter', 9770]
paired_example = [(x, example[i+1]) for i, x in enumerate(example) if type(x) is str]
# paired_example = [(danial, 5104), (peter, 9770)]

with open("example.csv", "w") as file:
    fieldnames = ['name', 'number']
    writer = csv.DictWriter(file, fieldnames)
    writer.writeheader()
    for item in paired_example:
        writer.writerow({'name': item[0], 'number': item[1]})

Final note, I would modify the code that produces list= [‘danial’, 5104, ‘peter’, 9770] to store this information as ‘pairs’ (tuple, dictionary, whatever) from the start, rather than reorganizing the items downstream. If your list has missing values, it’s probably going to lead to IndexErrors or pairing two names together – a more error resistant pairing method might be advisable.