如何将以下字典打印到csv文件中?
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
因此,输出CSV如下所示:
test1, alpha, 2
test2, gamma, 2
答案 0 :(得分:6)
import csv
with open("data.csv", "wb") as f:
csv.writer(f).writerows((k,) + v for k, v in maxDict.iteritems())
答案 1 :(得分:1)
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
csvData = []
for col1, (col2, col3) in maxDict.iteritems():
csvData.append("%s, %s, %s" % (col1, col2, col3))
f = open('test.csv', 'w')
f.write("\n".join(csvData))
f.close()