在python中将dictionary转换为csv而不使用panda



我有dictionay列表,如下所示:

{'match':['football','cricket','baseball'],'player':['2','11','8']}

我想把这本字典转换成csv,但不用panda。

我的代码:

import csv
my_dictionary = {'match':['football','cricket','baseball'],'player'['2','11','8']}
with open('data.csv', 'w') as f:
for key in my_dictionary.keys():
f.write("%s, %sn" % (key, my_dictionary[key]))

我希望看到的输出:

match     player
football   2
cricket    11
baseball   8

因此,如果您想使用您的技术,您可以首先将所有键作为头写入第一行,然后在列表中迭代其余行,如下所示:

import csv
my_dictionary = {'match':['football','cricket','baseball'],'player':['2','11','8']}
with open('data.csv', 'w') as f:

headers = ', '.join(my_dictionary.keys()) + 'n'
f.write(headers)

for row in zip(*my_dictionary.values()):
string_row = ', '.join(row) + 'n'
f.write(string_row)

输出:

match, player
football, 2
cricket, 11
baseball, 8

使用zip将这两个列表('match','player'(组合为元组列表。用,连接每个元组。然后简单地将其中的每一个写入文件。

import csv
my_dictionary = {'match':['football','cricket','baseball'],'player':['2','11','8']}
zipList = list(zip(my_dictionary['match'],my_dictionary['player']))
zipList = [','.join(x) for x in zipList]

with open('data.csv', 'w') as f:
headers = ','.join(my_dictionary.keys()) + 'n'
f.write(headers)
for each in zipList:
f.write("%sn" % (each))

为了避免使用Pandas,请使用内置的CSV库:

import csv

my_dictionary = {'match':['football','cricket','baseball'],'player':['2','11','8']}
with open('output.csv', 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(my_dictionary.keys())
csv_output.writerows([*zip(*my_dictionary.values())])

这将产生包含:的output.csv

match,player
football,2
cricket,11
baseball,8

字典键提供了标题,如果使用标准的*zip(*xxx)技巧来转换条目,则可以一次性写入所有行。

相关内容

  • 没有找到相关文章