[Tutor] referencing vars()

Kent Johnson kent37 at tds.net
Sat Sep 15 22:30:05 CEST 2007

John wrote:
>         #Set up writer
>         import csv
>         vardict=vars()
>         for var in vardict:
>                 if var=='allcum' or var=='alldhdt':
>                         outfile=in_path+'/'+dataset+'_'+str(var)+'.csv'
>                         writer = csv.writer(open(outfile, "wb"))
>                         writer.writerows(var)
> I'm trying to do the above, but of course get an error because vardict 
> is only referencing vars(), thus changes size... also, I tried 
> vardict=[vars()], but this fails as well??

I'm not too clear what you are trying to do here. Do you want the values 
of the variables allcum and alldhdt?

vars() gives you a dict whose keys are varible names and values are, 
well, the values. I think you are trying to write the contents of allcum 
to a file with allcum in the name?

You could do it with vars like this:

         for var in ['allcum', 'alldhdt']:
                 writer = csv.writer(open(outfile, "wb"))

or you could iterate a list of name, value tuples directly:

         for name, value in [('allcum', allcum), ('alldhdt', alldhdt)]:
                 writer = csv.writer(open(outfile, "wb"))

I think I prefer the second, even with the duplication of names; it 
feels more explicit to me.

Another alternative would be to accumulate the values in a dict with 
keys 'allcum' and 'alldhdt'. Then you would look up in that dict instead 
of in vars().


More information about the Tutor mailing list