[Tutor] referencing vars()

John washakie at gmail.com
Mon Sep 17 08:59:02 CEST 2007


Kent,

Thanks this is exactly the solution I am looking for...  so simple.


On 9/15/07, Kent Johnson <kent37 at tds.net> wrote:
>
> 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']:
>                 outfile=in_path+'/'+dataset+'_'+var+'.csv'
>                 writer = csv.writer(open(outfile, "wb"))
>                 writer.writerows(vars()[var])
>
> or you could iterate a list of name, value tuples directly:
>
>         for name, value in [('allcum', allcum), ('alldhdt', alldhdt)]:
>                 outfile=in_path+'/'+dataset+'_'+name+'.csv'
>                 writer = csv.writer(open(outfile, "wb"))
>                 writer.writerows(value)
>
> 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().
>
> HTH,
> Kent
>



-- 
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Five 1.4.1,
Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
4.1.1-51)],
PIL 1.1.6
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070916/e16df154/attachment.htm 


More information about the Tutor mailing list