create dynamic variable names in Python

Question:

Here is a very simple example of creating a variable in Python:

model_result = 5

Now the problem is that, I need to run a same snippet of codes for a lot of model scenarios, and save out the final result from each scenario with a corresponding name.

When using this snippet of codes, I will only update the chosen scenario using a hashtag (#), and keep the remaining analysis codes untouched. For example:

# pick a scenario
chosen_scenario = "baseline"
#chosen_scenario = "test1"
#chosen_scenario = "test2"
#chosen_scenario = "test3"
#chosen_scenario = "test4"
#chosen_scenario = "test5"
print("Chosen scenario:",chosen_scenario)

# move to the corresponding directory and get the files
Target_files = sorted(glob.glob("C:/model-outputs/"+chosen_scenario+"_output/model_output_*.csv"))

# Then run through some fixed routine analysis

At the end of the snippet, I want to save out the variable direclty as something like:
model_result_baseline,model_result_test1,model_result_test2, instead of manually typing them every time. Because there are a lot of scenarios.

Is this possible in Python?

Many thanks.

Asked By: Jeremy

||

Answers:

You question needs clarification but is below what you ask for ?

Put scenarios in list

scenarios = ["baseline", "test1"]

then run your script in for loop;

for scenario in scenarios:
    Target_files = sorted(glob.glob("C:/model-outputs/" + scenario + "_output/model_output_*.csv"))

Also when you put them in list instead using hashtag to comment out other scenarios you can access the scenario you want by using list index;

scenarios[index]
Answered By: Lanre

I recommend using a dictionary to achieve what you are trying to do:

results = {}
scenarios = ['baseline', 'test1', 'test2', 'test3']
for s in scenarios:
    results[s] = sorted(glob.glob(f"C:/model-outputs/{s}_output/model_output_*.csv"))
Answered By: TrimPeachu

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

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

Check my post for some more details.

Answered By: higee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.