Python: How to write a dictionary of tuple values to a csv file?

与世无争的帅哥 提交于 2019-12-04 04:44:21

问题


How do I print the following dictionary into a csv file?

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

So, that the output CSV looks as follows:

test1, alpha, 2
test2, gamma, 2

回答1:


import csv
with open("data.csv", "wb") as f:
    csv.writer(f).writerows((k,) + v for k, v in maxDict.iteritems())



回答2:


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


来源:https://stackoverflow.com/questions/5530619/python-how-to-write-a-dictionary-of-tuple-values-to-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!