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!
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.