0

To be able to increase my dictionary while not changing much else in the code, I want to iterate through the dictionary keys and create dataframes.

The way I have found is through creating global variables with global(). However, is this the most pythonic way, or the best way? I know global variables are a nono, but it seems to be the only fix here.

stocks = {
    'Tencent':'TCEHY',
    'Blizzard' : 'ATVI',
    'EA':'EA',
    'Rockstar':'TTWO'
}

def create_dataframes(stock_dict):
    for stock in stock_dict:
        globals()[stock] = pd.read_csv('{}.csv'.format(stock_dict[stock]))

This results in new variables with the key names, which is of course what I want. I just want to know if I should do this in another way?

Thanks!

4
  • 2
    you could easily use the dictionary directly
    – Netwave
    Oct 23, 2019 at 9:27
  • 3
    The most pythonic way is to use dictionary for dynamic names, and not create globals in runtime.
    – bereal
    Oct 23, 2019 at 9:27
  • @Netwave What do you mean with using it directly? I'm loading the variables with a full dataframe, so I can further analyze them with their respective names. Oct 23, 2019 at 9:28
  • @Dansekongen, exactly what bereal said.
    – Netwave
    Oct 23, 2019 at 9:42

1 Answer 1

4

Don't create global variables at runtime, just use a dictionary.

dfs = {}
for stock_name, stock_code in stock_dict.items():
    dfs[stock_name] = pd.read_csv(f'{stock_code}.csv')

You can then access them using their names

dfs['EA'].describe()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.