Python: 将字典转换成csv文件

Python: convert dictionary into a cvs file

这是我当前的代码:

import csv
data = {'name' : ['Dave', 'Dennis', 'Peter', 'Jess'],
        'language': ['Python', 'C', 'Java', 'Python']}

new_data = []
for row in data:
    new_row = {}
    for item in row:
        new_row[item['name']] = item['name']
    new_data.append(new_row)

print(new_data)
header = new_data[0].keys()
print(header)

with open('output.csv', 'w') as fh:
    csv_writer = csv.DictWriter(fh, header)
    csv_writer.writeheader()
    csv_writer.writerows(new_data)

我想要实现的是将字典键转换为 csv headers 并将值转换为行。

但是当 运行 代码时,我在第 21 行得到 TypeError: 'string indices must be integers'

问题

这里的问题是for row in data。这实际上是迭代 data 字典的键,然后迭代字典键的字符:

In [2]: data = {'name' : ['Dave', 'Dennis', 'Peter', 'Jess'],
   ...:         'language': ['Python', 'C', 'Java', 'Python']}
   ...:
   ...: new_data = []
   ...: for row in data:
   ...:     for item in row:
   ...:         print(item)
   ...:
n
a
m
e
l
a
n
g
u
a
g
e

方法

您实际需要做的是使用zip同时捕获每个人的姓名和最喜欢的语言:

In [43]: for row in zip(*data.values()):
    ...:     print(row)
    ...:
('Dave', 'Python')
('Dennis', 'C')
('Peter', 'Java')
('Jess', 'Python')

现在,您需要 zip 这些元组的键来自 data:

In [44]: header = data.keys()
    ...: for row in zip(*data.values()):
    ...:     print(list(zip(header, row)))
    ...:
[('name', 'Dave'), ('language', 'Python')]
[('name', 'Dennis'), ('language', 'C')]
[('name', 'Peter'), ('language', 'Java')]
[('name', 'Jess'), ('language', 'Python')]

解决方案

现在您可以将这些元组传递给 dict 构造函数以创建您的 rowdictscsv_writer.writerows 需要:

header = data.keys()
new_data = []
for row in zip(*data.values()):
    new_data.append(dict(zip(header, row)))

with open("output.csv", "w+", newline="") as f_out:
    csv_writer = csv.DictWriter(f_out, header)
    csv_writer.writeheader()
    csv_writer.writerows(new_data)

output.csv中的输出:

name,language
Dave,Python
Dennis,C
Peter,Java
Jess,Python