Reputation: 2145
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, test2
alpha, gamma
2, 2
p.s. I have asked this question before but not sure how to rearrange it in another way, i.e. tranposed.
Upvotes: 0
Views: 427
Reputation: 287885
You should be aware that the order of keys in a dict is implementation-defined, i.e. random. Therefore, it's advisable to sort them. Other than that, simply using the csv
module should work:
import csv
maxDict = {'test1': ('alpha', 2), 'test2': ('gamma', 2)}
keys = sorted(maxDict.keys())
csvw = csv.writer(open('output.csv', 'wb'))
csvw.writerow(keys)
data = [maxDict[k] for k in keys]
for row in zip(*data):
csvw.writerow(row)
Upvotes: 4