Dynamic Variable in Python

How can you dynamically create variables?

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.

how to create variable names dynamically and assigning values in python?

As noted in RunOrVeith's answer, a Dict is probably the right way to do this in Python. In addition to eval, other (non-recommended) ways to do this including using exec or setting local variables as noted here

stri = "mat"

for i in range(1,3):
exec("_".join([stri, str(i)])+'=1')

or locals,

stri = "mat"

for i in range(1,3):
locals()["_".join([stri, str(i)])] = 1

This define mat_1 = 1 and mat_2 = 1 as required. Note a few changes to your example (str(i) and range(1,3) needed, for python3 at least).

I want to create a dynamic variable and use it

Short answer, do not do this!

It is widely accepted to be a bad practice (see for example). You have a high risk of doing something difficult to debug, to overwrite existing variables, or to use the wrong namespace. In addition there are eventual pitfalls and lack of robust methods to do this.

Use a container instead.
You will have a shorter, cleaner, and easier to debug code.

Dictionaries are ideal for this:

# initialize
my_dfs = {}

# computation
for i in …:
my_dfs[f'df_computation_{i}'] = …

# access
my_dfs['df_computation_42']

create dynamic variable names in Python

You could achieve this by adding variables dynamically to global/local dictionary using globals() or locals() or vars()

for chosen_scenario in scenarios:
path = "C:/model-outputs/" + chosen_scenario + "_output/model_output_*.csv"
globals()[chosen_scenario] = sorted(glob.glob(path))

Check my post for some more details.

Dynamic Variable Parameter Python

You can do:

...
variable_weeks = 'weeks'
next_month = today + relativedelta(**{variable_weeks: loop})
...

This uses a dict for the key-value pairs that you can define with variables. The dict is then unpacked as the input for relativedelta.

How to filter list by comma and append the value to dynamic variable in Python

You can create variables as such

data = [('xxx@gmail.com', '111@gmail.com\n', '{ "header1": "Subject", "header2": "Text"}', ' { "condition1": "Equal", "condition2": "Contain"}', '{ "parameter1": "hi1", "parameter2": "hi2" || "testNested"}', '{ "subjectP1": "WorkedDynamicWord","wordP1": "hi1","subjectP2": "WorkedDynamicWord2", "wordP2": "Dynamic word"}'), ('xxx@yahoo.com', '111@gmail.com\n', '{ "header1": "Subject"}', '{ "condition1": "Contain"}', '{ "parameter1": "haha"}', None)]

for i,l in enumerate(data):
vars()[f'variable{i + 1}'] = l

print(variable1, variable2)


Related Topics



Leave a reply



Submit