I'm trying to dynamically create variable names in a for loop. In the contrived example below, I simply want to create a separate dataframe for each ticker:
tickers = ['FB', 'AMZN', 'NFLX', 'GOOG']
for ticker in tickers:
'df_' + ticker = pd.read_excel('my_data.xlsx', sheet_name=ticker)
#SyntaxError: can't assign to operator
However, this seems to work:
for ticker in tickers:
locals()['df_' + str(ticker)] = pd.read_excel('my_data.xlsx', sheet_name=ticker)
I've seen similar examples of this question posted previously, but responses range from dicts, to locals, to setattr. I'm trying to learn and understand the most Pythonic way to handle this. Hard for me to understand from others' examples and often responses that suggest a non-optimal way of handling.