[Tutor] Writing a csv from a dictionary

Mark Tolonen metolone+gmane at gmail.com
Tue Jun 23 07:08:52 CEST 2009


"Eduardo Vieira" <eduardo.susan at gmail.com> wrote in message 
news:9356b9f30906221404o7a7c5e5dt3d59e7b6d40accd0 at mail.gmail.com...
> 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





More information about the Tutor mailing list