Python:如何将cuple值的字典写入csv文件?

时间:2011-04-03 15:48:20

标签: python csv dictionary tuples

如何将以下字典打印到csv文件中?

maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)} 

因此,输出CSV如下所示:

test1, alpha, 2
test2, gamma, 2

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()