用 Python 将列表字典写入 csv

Coo*_*eek 5 python csv dictionary python-2.7

我有一本类似的字典{a: [1, 2, 3], b: [4, 5, 6], c: [7, 3, 2]},我想将它写入 Python 中的 csv 文件。我是 csv 文件:

col1,col2,col3,col4
a,1,2,3
b,4,5,6
c,7,3,2
Run Code Online (Sandbox Code Playgroud)

我尝试使用 CSV Dict writer,但我无法获得,因为值是此处的列表。

任何帮助表示赞赏!

Mar*_*ans 5

您可以使用 Python 的csv库执行以下操作(对于 Python 3.x,请参见下文):

import csv

my_dict = {"a" : [1, 2, 3], "b" : [4, 5, 6], "c" : [7, 3, 2]}

with open("output.csv", "wb") as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['col1', 'col2', 'col3', 'col4'])
    
    for key in sorted(my_dict.keys()):
        csv_output.writerow([key] + my_dict[key])
Run Code Online (Sandbox Code Playgroud)

给你:

col1,col2,col3,col4
a,1,2,3
b,4,5,6
c,7,3,2
Run Code Online (Sandbox Code Playgroud)

.writerow()函数采用项目列表并将它们以正确格式写入输出 CSV 文件。由于您希望将键作为第一项,它会传递在字典中key查找时发现的与它们连接的项,从而产生您想要的输出。keymy_dict


注意:如果使用 Python 3.x,文件打开行需要修改,不需要排序:

with open("output.csv", "w", newline="") as f_output:
Run Code Online (Sandbox Code Playgroud)


Jor*_*ley 0

with open("out.csv","wb") as csv_out:
    # first the header
    csv_out.write(",".join("Col%d"%i for i in range(len(a_dict.values()[0]))+"\n")
    # then each row .... make sure its sorted by the keys ...
    for key,a_list in sorted(a_dict.items(),key=lambda row:row[0])
        x = [key,]
        x.extend(a_list)
        csv_out.write(",".join(str(i) for i in x)
Run Code Online (Sandbox Code Playgroud)