如何使用csv模块将多个有价值的字典写入csv?

import csv

dict = {'a':[1,4],'b':[2,3]}

我想将此模块转换为名称为“ rating.csv”的csv文件

所需的输出:

name,maths,science
a,1,4
b,2,3
xiong_yingwen 回答:如何使用csv模块将多个有价值的字典写入csv?

您可以遍历字典中的键和值,将二者结合到一个列表中,然后为每个条目使用csv.writerow

import csv
d = {'a':[1,4],'b':[2,3]}
with open("rating.csv","w",newline="") as fh:
    writer = csv.writer(fh)
    writer.writerow(["name","maths","science"])
    for key,values in d.items():
        writer.writerow([key] + values)

请注意,我已将dict重命名为d,因为您应该避免对变量使用内置名称。

“ rating.csv”中的输出:

name,maths,science                                                              
a,1,4                                                                           
b,2,3
本文链接:https://www.f2er.com/2504622.html

大家都在问