[Tutor] Writing a csv from a dictionary

Kent Johnson kent37 at tds.net
Tue Jun 23 13:15:05 CEST 2009


On Tue, Jun 23, 2009 at 1:08 AM, Mark Tolonen<metolone+gmane at gmail.com> wrote:

> 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])

I think I would write this as
for k, v in dyc.items(): # or iteritems()
  mywriter.writerow([k] + v)

That way it doesn't depend on the actual size of the value list.

Kent


More information about the Tutor mailing list