[英]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. 我正在尝试将此字典导出到
csv
文件中。 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. 为
DictWriter
提供了字段/列名称,并假定要作为字典提供的行具有与给定字段名称相对应的键。 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. 您可以使用简单的
csv.writer
因为您的行是给定字典的键和值的混合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.