I'm having trouble making a part of my code a little more efficient. What I'm trying to do, is add stock data with the 'yfinance' package to a Dash DataTable that contains the ticker name. What I have and what works fine is:
for row in asset_data:
info = yf.Ticker(row['ticker']).inf
row['product'] = info['longName']
row['currency'] = info['currency']
row['exchange'] = info['exchange']
row['price'] = info['regularMarketPrice']
return asset_data
Where 'ticker', 'product', 'currency', 'exchange' and 'price' are the corresponding column id's in the DataTable.
So, this works fine, but I feel that it should be possible to make the 'row[] = info[]' part more efficient (and flexible). I tried:
row['product', 'currency', 'exchange', 'price'] = info['longName', 'currency', 'exchange', 'regularMarketPrice']
This gives me the error: KeyError: ('longName', 'currency', 'exchange', 'regularMarketPrice').
I tried:
row['product', 'currency', 'exchange', 'price'] = info[{'longName', 'currency', 'exchange', 'regularMarketPrice'}]
This gives me the error TypeError: unhashable type: 'set'.
I also tried:
columns = {
'product': 'longName',
'currency': 'currency',
'exchange': 'exchange',
'price': 'regularMarketPrice'
}
row[columns.keys()] = info[columns.values()]
But that gives me a KeyError: dict_values(['longName', 'currency', 'exchange', 'regularMarketPrice']).
I feel like I'm being stupid for not understanding why these won't work, and it probably has something to do with trying to match incompatible classes, but I can't seem to figure it out. Can anyone give me a tip? Thanks!
Update: Using @metatoaster 's suggestion, my code now looks like this:
for row in asset_data:
info = yf.Ticker(row['ticker']).info
row.update(product=info['longName'], currency=info['currency'], exchange=info['exchange'],
price=info['regularMarketPrice'])
return asset_data
A little cleaner, just how I wanted it.