4

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
zpea
  • 1,072
  • 6
  • 23
siva
  • 2,105
  • 4
  • 20
  • 37
  • Hey siva! I see you got your answers, but next time please let us know what you tried yourself instead of asking others to write your code. In python there is a library for almost any common task. The one to write a csv file is named csv. That should be easy to find. And in case you where not stuck there but with extracting key and value pairs from dictionary your question should reflect that in some way. That said, have fun on SO. – zpea Jul 09 '12 at 14:28

2 Answers2

7
import csv
with open("data.csv", "wb") as f:
    csv.writer(f).writerows((k,) + v for k, v in maxDict.iteritems())
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • what is being written into a csv using the `writerows` method? is it a list? tuple? – siva Apr 03 '11 at 16:19
  • The generator expression in the above code feeds tuples to `writerows()`, but you could also use lists if you prefer. – Sven Marnach Apr 03 '11 at 16:24
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()
Prydie
  • 1,807
  • 1
  • 20
  • 30