If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:
globals()['somevar'] = 'someval'
print somevar # prints 'someval'
But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.
mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']
Learn the python zen; run this and grok it well:
>>> import this
Answer from kanaka on Stack OverflowIf you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:
globals()['somevar'] = 'someval'
print somevar # prints 'someval'
But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.
mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']
Learn the python zen; run this and grok it well:
>>> import this
Though I don't see much point, here it is:
for i in xrange(0, len(prices)):
exec("price%d = %s" % (i + 1, repr(prices[i])));
python - Automatic variable name generation - Stack Overflow
Automatic creating variables. Proper way with Python
Go to variable names?
creating different list names automatically
Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.
a = {}
k = 0
while k < 10:
# dynamically create key
key = ...
# calculate value
value = ...
a[key] = value
k += 1
There are also some interesting data structures in the collections module that might be applicable.
globals() returns a dictionary of the module's variables. You can create a new variable by creating a key on that dictionary:
# By default, a module has some hidden variables defined
print({k: v for k, v in globals().items() if not k.startswith("__")})
for i in range(1, 11):
globals()[f"my_variable_{i}"] = i
print()
print(my_variable_1)
print(my_variable_2)
# and so on
print()
print({k: v for k, v in globals().items() if not k.startswith("__")})
Result:
{}
1
2
{'i': 10, 'my_variable_1': 1, 'my_variable_2': 2, 'my_variable_3': 3, 'my_variable_4': 4, 'my_variable_5': 5, 'my_variable_6': 6, 'my_variable_7': 7, 'my_variable_8': 8, 'my_variable_9': 9, 'my_variable_10': 10}
You can use the built-in setattr function.
setattr(x, 'foobar', 123)is equivalent tox.foobar = 123.
for key, value in dict.items():
setattr(self, f'var_{key}', value)
Please try this. I hope this is what you need.
dict_source={1:'A',2:'B',3:'C'}
name=[]
dict_final={}
for i in range(1,4):
var_name='var_{}'.format(i)
name.append(var_name)
dict_final[name[i-1]]=dict_source[i]
Hi,
I have no formal education in programming and I struggle with the idea of "automatic creation of variables". What I understand by that is: a method of putting a name and value in to a variable, I could use later, other than plain assignment with =.
I have come to believe that whenever I feel need to do something like that it is poor design. And I shouldnโt.
But what can I do when, for example, I want to create 9 symbolic variables to play with SymPy. A symbolic variable is done by:
F1 = sympy.Symbol('F1')Ok, but i want 9 of them and I don't want to write 9 similar lines of code. I figured I can make list of names:
list_of_variables = ['F{}'.format(i) for i in range(9)]Than something Iโm guessing is wrong (like bad behaviour)
for name in list_of_variables:
exec(name+' = sm.Symbol('+'name'+')')It gets me what I want but is it right way to do so ?