How can you dynamically create variables? [duplicate]

I want to create variables dynamically in Python. Does anyone have any creative means of doing this?


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 new 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}

Use the exec() method to run arbitrary code. For example, say you have a dictionary and you want to turn each key into a variable with its original dictionary value, you can do the following:

>>> c = {"one": 1, "two": 2}
>>> for k, v in c.items():
...     exec(f"{k} = {v}")
... 
>>> one
1
>>> two
2

Stuffing things into the global and/or local namespaces is not a good idea. Using a dict is so some-other-language-ish ... d['constant-key'] = value just looks awkward. Python is OO. In the words of a master: """Namespaces are one honking great idea -- let's do more of those!"""

Like this:

>>> class Record(object):
...     pass
...
>>> r = Record()
>>> r.foo = 'oof'
>>> setattr(r, 'bar', 'rab')
>>> r.foo
'oof'
>>> r.bar
'rab'
>>> names = 'id description price'.split()
>>> values = [666, 'duct tape', 3.45]
>>> s = Record()
>>> for name, value in zip(names, values):
...     setattr(s, name, value)
...
>>> s.__dict__ # If you are suffering from dict withdrawal symptoms
{'price': 3.45, 'id': 666, 'description': 'duct tape'}
>>>

vars()['meta_anio_2012'] = 'translate'