On 7 mar, 16:23, Andreas Waldenburger <use...@geekmail.invalid> wrote: > On Sun, 7 Mar 2010 07:05:26 -0800 (PST) vsoler > > > > <vicente.so...@gmail.com> wrote: > > Hello, > > > My script starts like this: > > > book=readFromExcelRange('book') > > house=readFromExcelRange('house') > > table=readFromExcelRange('table') > > read=readFromExcelRange('read') > > ... > > > But I would like to have something equivalent, like... > > > ranges=['book','house','table','read'] > > for i in ranges: > > var[i]=readFromExcelRange(i) > > > which does not work. I assume I should be using globals() instead of > > var, but I do not know how to write my script. > > > Can anybody help? > > One additional line, and it works (all the following code is untested, > I might have goofed it up somewhere, but you get the idea): > > ranges=['book','house','table','read'] > var = {} > for i in ranges: > var[i]=readFromExcelRange(i) > > Or, more succinctly: > > var = dict((i, readFromExcelRange(i)) for i in ranges) > > although that looks a bit crowded. Perhaps > > rd = readFromExcelRange > var = dict((i, rd(i)) for i in ranges) > > looks better, but not by much, IMO. > > In Python 3 you can also just say > > var = {i:readFromExcelRange(i) for i in ranges} > > (I think. I don't have Python 3.) This looks comparatively neat, > because there are no nesting parens. > > And just in case you think it's a good idea to meddle with globals and > create actual "variables": it's not. You absolutely want dictionaries > here. It's basically a bad idea to create names *implicitly* that > you're going to use *explicitly*. (That is, it is in Python anyway, > because it does not provide a clean and clear way of doing this. Other > languages might provide that sort of thing, and it might be awesome, > but in Python, no sir.) > > /W > > -- > INVALID? DE!
Thank you Andreas. Your comprehensive answer makes a lot of sense to me. -- http://mail.python.org/mailman/listinfo/python-list