Skip to content Skip to sidebar Skip to footer

Python: How To Write A Dictionary Of Tuple Values To A Csv File?

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,

Solution 1:

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

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

Post a Comment for "Python: How To Write A Dictionary Of Tuple Values To A Csv File?"