简体   繁体   中英

Exporting a complicated dictionary into a csv file

I have a dictionary in which the values are list. here is an example:

example:

d = {'20190606_CFMPB576run3_CF33456_12.RCC': [1.0354477611940298, '0.51'],
     '20190606_CFMPB576run3_CF33457_05.RCC': [1.0412757973733584, '1.09'],
     '20190606_CFMPB576run3_CF33505_06.RCC': [1.0531309297912714, '0.81']}

I am trying to export this dictionary into a csv file. like this expected output:

expected output:

file_name,citeria1,criteria2
20190606_CFMPB576run3_CF33456_12.RCC,1.0354477611940298, 0.51
20190606_CFMPB576run3_CF33457_05.RCC,1.0412757973733584,1.09
20190606_CFMPB576run3_CF33505_06.RCC,1.0531309297912714,0.81

to do so, I made the following code:

import csv

with open('mycsvfile.csv', 'w') as f:
    header = ["file_name","citeria1","criteria2"]
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(d)

but it does not return what I want. do you know how to fix it?

Change as follows:

import csv

with open('mycsvfile.csv', 'w') as f:
    header = ["file_name", "citeria1", "criteria2"]
    w = csv.writer(f)
    w.writerow(header)
    for key, lst in d.items():
        w.writerow([key] + lst)

A DictWriter is given the field/column names and assumes the rows to be provided as dictionaries with keys corresponding to the given field names. In your case, the data structure is different. You can use a simple csv.writer as your rows are a mixture of keys and values of your given dictionary.

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