NEW TO THIS: Assigning values to strings in list?

Alex Martelli aleax at aleax.it
Sat Jul 20 03:44:27 EDT 2002


Justin Shaw wrote:

>> Basicely I have two lists, one containing the future string-names
>> and one containing the values I want to give them. The order is
>> identical in both. Right now I'm solving this by a dictionary, but
>> I would really prefer to have straight strings as a result of my
>> operation.
> 
> I like the idea of keeping your namespace clean.  But if what you really
> want is to assign the values to your local namespace I have two solutions.
> 
> 1. Ugly one-liner
> eval ';'.join(['='.join(x) for x in zip(names, [str(v) for v in values])])

Can't work -- eval only works on expressions, not statements.  I
guess you mean exec (shudder).

> 2. Update locals()
> locals().update(dict(zip(names,values)))

Wont' work in typical functions -- treat locals() as read-only,
mods to it won't necessarily "take" anyway.  I'd like locals()
to return a R/O dict proxy -- errors should not pass silently,
and this one definitely IS an error.

Working on a dict is BY FAR the best idea, cleanest and fastest.

If the OP is truly intent on damaging code quality while
making performance substantially worse, something like your
first suggestion with exec in instead of eval might work
(you probably want to s/str/repr/ too).  *shudder*.  The
lengths to which people will go seeking self-destruction...!-(


Alex




More information about the Python-list mailing list