"Eduardo Vieira" <[email protected]> wrote in message news:[email protected]...
Hello, I have a dictionary similar to this:
dyc = {
'a50' : ['textfield', 50, 40],
'k77' : ['othertext', 60, 10]
}

I was trying to write a csv with the csv module, by doing this:
import csv
myfile = open('c:/myscripts/csv-test.csv', 'wb')
mywriter = csv.writer(myfile, dialect='excel')

for item in dyc:
mywriter.write(item)

myfile.close()

this gives me this result:
a50,"['textfield', 50, 40]"
k77,"['othertext', 60, 10]"

I would like this, instead:
a50,"textfield", 50, 40
k77,"othertext", 60, 10

It's a good idea to cut-and-paste actual code and actual output. Your above code doesn't work. "writerow" is the correct method and "for item in dyc.items():" is needed to iterate over keys and values correctly.

import csv

dyc = {
'a50' : ['textfield', 50, 40],
'k77' : ['othertext', 60, 10]
}

myfile = open('csv-test.csv', 'w')
mywriter = csv.writer(myfile, dialect='excel')

for k,[a,b,c] in dyc.items():
   mywriter.writerow([k,a,b,c])

myfile.close()

OUTPUT:

a50,textfield,50,40
k77,othertext,60,10

If you want quoted text fields use:

mywriter = csv.writer(myfile, dialect='excel',quoting=csv.QUOTE_NONNUMERIC)

-Mark



_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to