Python:将dictionary转换为cvs文件



这是我当前的代码:

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标题,并将值转换为行。

但是当运行代码时,我在第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')

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

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构造函数来创建csv_writer.writerows需要的rowdicts:

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

相关内容

  • 没有找到相关文章