开发者

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

开发者 https://www.devze.com 2023-02-21 14:11 出处:网络
How do I print the following dicti开发者_JAVA技巧onary into a csv file? maxDict = {\'test1\': (\'alpha\', 2), \'test2\': (\'gamma\', 2)}

How do I print the following dicti开发者_JAVA技巧onary 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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号