0

I have an imports dictionary with:

  • keys equal to names of new variables I would like to build, for example dataset_1, dataset_2 etc.
  • values being the pandas DataFrames (the type of each value is pd.DataFrame)

What I would like to achieve is to build new variables in amount of len(keys). The name of each variable would be equal to the name of key and the variable would hold a respective pd.DataFrame.

The code below doesn't work, but nevertheless, I have deep feeling that still it's a bad approach and a 'regular programmer' would do this another way.

for key in imports.keys():
    import_str = '{} = imports.get({})'.format(key, key)
    globalize = 'global {}'.format(key)
    
    exec(globalize)
    exec(import_str)

Can you please advise how to proceed?

markoo
  • 19
  • 3
  • 2
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – Carcigenicate Sep 28 '20 at 13:43
  • 1
    You'd use a dictionary in this case. Trying to dynamically create variables is indeed poor practice. – Carcigenicate Sep 28 '20 at 13:43
  • Thanks @Carcigenicate for answer. This is what I did, but it's not my goal since the variables are stored in dictionary and I want to have them 'globally' accessible within my program. I agree my approach is silly, but I don't have any idea how to make it in another way. If you could point me someway, I'd be more than grateful. – markoo Sep 28 '20 at 14:11
  • That's still possible. If the dictionary is global, so will be all of its contents. I'd rethink that design too though. Having mutable data globally available is a recipe for confusing code and hard to track bugs. If you have functions that require the data, ideally, the data should be supplied as arguments to the function. – Carcigenicate Sep 28 '20 at 14:13
  • What do you mean by mutable data? Regards the dictionary - how would you proceed from having following dictionary called imports with for example keys: Poland, Germany, France and values: pd.DataFrame, pd.DataFrame, pd.DataFrame to having them as separate variables so that for example I can run code Poland.head() instead of imports.get('Poland').head()? – markoo Sep 29 '20 at 14:20

0 Answers0