简体   繁体   中英

iterating over dictionary values and writing into csv files: Python 3.6

Trying to write contents of a dictionary into a .csv file. The dictionary values are tuples. I want each row to contain a key and then iterate over the values and write each in a separate field in the same row:

I wrote this function (where v is a tuple):

def csv_writer(dict, filename):
    with open(filename, 'w') as f:   
        w = csv.writer(f)
        for k,v in dict.items():
            w.writerow([k, v])

the contents of v appear as a tuple in the csv file, but I want to get something like this:

k1  v1 v2 v3 v4
k2  v1 v5 v6 

etc.

Thanks for any tips in advance.

def csv_writer(dict, filename):
    with open(filename, 'w') as f:   
        outfile = csv.writer(f)
        for k,v in dict.items():
            outfile.writerow([k] + v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM