Home > Net >  How to write to csv dict in one line
How to write to csv dict in one line

Time:01-31

I have a dictionary {k1:1, k2:2, k3:3 } How can I write it to csv in this form |k1|1|k2|2|k3|3 Already tried all the options, the maximum that happened enter image description here

CodePudding user response:

you can do it like this

def write_to_csv_one_line(dictionary, file_path):
    with open(file_path, 'w') as f:
        f.write(','.join([','.join(item) for item in dictionary.items()]))

CodePudding user response:

You could use a CSV writer and the Python chain() function as follows:

from itertools import chain
import csv

my_dict = {"k1" : 1, "k2" : 2, "k3" : 3}

with open('output.csv', 'w', newline='') as f_output:
    csv.writer(f_output).writerow(chain.from_iterable(my_dict.items()))

Giving an output of:

k1,1,k2,2,k3,3
  •  Tags:  
  • Related