如何使用 csv 模块将多值字典写入 csv?

How to write multiple valued dictionaries to csv using csv module?

import csv

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

我想将此模块转换为名称为 'rating.csv'

的 csv 文件

期望的输出:

name,maths,science
a,1,4
b,2,3

您可以遍历字典键和值,将两者连接到一个列表中,然后对每个条目使用 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