Search code examples
python-3.xkeyerroryfinance

In case of Python KeyError, how to return a value of None if a key does't exist


In my case, I have an empty dictionary which I want to fill with Key:Value pairs about stock tickers information. I tested the code below but I always get a KeyError message whenever a key is missing from the list of tickers I loop through. All I want is to set a group of default Keys for all my tickers (Info_data in the code below), then set the value of the missing "Key" to "None" whenever it finds a missing key.

Here is my code:

stocks_info = {}
for symbol in tqdm(sav_set):
    info = yf.Tickers(symbol).tickers[symbol].info
    if info['quoteType'] == 'EQUITY':
        info_data = {'symbol': symbol, 'shortName': info['shortName'], 'country': info['country'],
                     'sector': info['sector'], 'industry': info['industry'], 'marketCap': info['marketCap'],
                     'currentPrice': info['currentPrice'], 'quoteType': info['quoteType'], 'market': info['market']}

Solution

  • Many thanks to @dawg for providing help. This is how I managed to resolve my issue:

    stocks_info = {}
    for symbol in tqdm(sav_set):
        info = yf.Tickers(symbol).tickers[symbol].info
        # info_keys = {'symbol', 'shortName', 'longName', 'country', 'sector', 'industry', 'marketCap', 'currentPrice',
        #              'navPrice', 'quoteType', 'market'}
    
        ticker = info.get('symbol', None)
        shortName = info.get('shortName', None)
        longName = info.get('longName', None)
        country = info.get('country', None)
        sector = info.get('sector', None)
        industry = info.get('industry', None)
        marketCap = info.get('marketCap', None)
        currentPrice = info.get('currentPrice', None)
        navPrice = info.get('navPrice', None)
        quoteType = info.get('quoteType', None)
        market = info.get('market', None)
    
        if info['quoteType'] == 'EQUITY':
            info_data = {'symbol': ticker, 'shortName': shortName, 'longName': longName, 'country': country,
                         'sector': sector, 'industry': industry, 'marketCap': marketCap, 'currentPrice': currentPrice,
                         'quoteType': quoteType, 'market': market}
        else:
            info_data = {'symbol': ticker, 'shortName': shortName, 'longName': longName, 'country': country,
                         'sector': sector, 'industry': industry, 'marketCap': marketCap, 'currentPrice': navPrice,
                         'quoteType': quoteType, 'market': market}
    
        stocks_info[symbol] = info_data
        json_object = json.dumps(stocks_info)
        with open("../tickers_data/stocks_info.json", "w") as outfile:
            outfile.write(json_object)