Python wrote:
> On Thu, 2006-10-05 at 09:17 -0500, Luke Paireepinart wrote:
> (actually from Frank)
>>> I have a parameterized string template, I publish it using
>>>
>>>   print mytemplate % locals()
> Original post asked to create variable in local namespace from string.
>> so I want to assign a value to a variable whos name is available only
>> as a string to me. 
>> that variable does not exist yet in the local namespace.
>>
>> from: t = "myvar"
>> to: myvar = 3
> 
> You can do something like:
>       templatevars = dict(locals())   # copy of locals
>       templatevars[t] = 3
>       print mytemplate % templatevars
> 
> It is OK for templatevars to have extra variables.  You will get a
> KeyError if templatevars is missing a value.

A slight variation, if you have multiple values you want to accumulate 
in a dict, would be something like this using dict.update():

templatevars = {}
...
templatevars['t'] = 3
...
templatevars['u'] = 4
...
templatevars.update(locals())
print mytemplate % templatevars

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to