views:

158

answers:

4

I would like to insert the value of a variable into the name of another variable in python. In a shell script this would be something like:

for n in `more list`  
do  
var_$n = some_calculation  
done

but I can't see how to do a similar thing in python. Is there a way or should I be using an alternative approach?
thanks,
Andy

A: 

a dict is one way to maintain an associative array.

dict = {}
dict[str] = calc();
Never name your dict "`dict`"; this shadows the builtin `dict`, which is the dictionary type, which you may need to call at some point.
Mike Graham
+6  A: 

Don't do it! Having variable names that change depending on the value of a variable leads to unnecessary complications. A cleaner way is to use a dictionary:

vr={}
for n in alist:
    vr[n]=some_calculation()
unutbu
Thanks! (and to other replies). This looks less fragile than my shell script approach too.
AndyC
A: 

Maybe not perfect, but two possible solutions:

>>> name = "var_1"
>>> locals()[name] = 5
>>> print var_1
5
>>> exec(name + "= 6")
>>> print var_1
6
But be aware that the `locals()` approach does not work inside functions. See here: http://forums.devshed.com/python-programming-11/dynamic-variable-declaration-140173.html It is still valid, I tested it.
Felix Kling
A: 
for n in more_list:
    globals()["var_"+str(n)]=some_calculation
ghostdog74