-1

I have the following code.


dict_of_df={}
for i in range(100):
    get_data = [data for data in cur]
    df = pd.DataFrame(get_data)
    dict_of_df[f"df_{i}"] = df

This gives me a dictionary of 100 dataframes. However, I need to assign each dataframe to a variable for it to be recognised and imported into another program (Microsoft Power BI). Is there a way I can assign each dataframe in the dictionary to a unique variable? Based on what I've read here How to create a new dataframe with every iteration of for loop in Python , a dictionary is the only way of storing the dataframe from each iteration but I need a way to extract it to my workspace.

XYZ123
  • 79
  • 7
  • a simple search turns this up: https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop in short; it's not a good idea – RedM Feb 21 '22 at 14:31
  • Dicts is how you properly handle "variable variables" in Python. I don't know anything about Power BI, but it's weird to me that it forces you to create hundreds of names in your program. Are you sure that's the only way? – timgeb Feb 21 '22 at 14:33
  • @timgeb Well PowerBI only supports importing dataframes into a dataset unfortunately so this is my only option, no matter how badly optimised it will be. Is there a way to do it then? – XYZ123 Feb 21 '22 at 14:42

1 Answers1

2

Use globals() to create your variables dynamically. Use with caution, it's not really a good practice but it should work:

for i in range(100):
    get_data = [data for data in cur]
    df = pd.DataFrame(get_data)
    globals()[f"df_{i}"] = df  # <- replace your dict by globals()
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Corralien, why using `globals()` may not be a good practice ? – Timeless Jan 14 '23 at 13:41
  • 1
    @Timeless. It's not really a bad practice if you control your code and not sharing to other :-). You can create bad named variable like `globals()['***'] = 123`. Now you have a variable named `***` which is unusable. – Corralien Jan 14 '23 at 14:14