0

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.

msnackey
  • 1
  • 1
  • You really don't have a shortcut aside from calling [`row.update`](https://docs.python.org/3/library/stdtypes.html#dict.update) with a new dictionary or a key/value pair, e.g `row.update(product=info['longname'], ...)`. Otherwise if renaming the keys is not needed you may just `row.update(info)`. If the source dictionary (in your case, `info`) contains many keys but only one needs renaming, just [rename](https://stackoverflow.com/questions/16475384/rename-a-dictionary-key) the affected ones and then call `row.update(info)`. – metatoaster Jun 20 '22 at 02:19
  • @metatoaster Cheers, this worked! Edited my post to reflect how my current code looks. Thanks :) – msnackey Jun 24 '22 at 11:14

0 Answers0