You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码出现KeyError: ['logo_url'] not in index错误,求解决方案

解决方案:KeyError: ['logo_url'] not in index

问题原因

yfinance返回的股票信息字典ticker.info里,logo_url字段并非所有股票都提供,部分股票的信息中没有这个字段,直接转成DataFrame后访问该列就会触发KeyError。另外你代码里的df[["logo_url", "shortName", "longBusinessSummary"]]这行完全没用,既没赋值也没做任何操作,可以删掉。

解决步骤

  • 直接操作ticker.info字典,用get方法安全获取字段,避免KeyError
  • 为缺失的字段设置默认值(比如空字符串或提示文本)
  • 去掉不必要的DataFrame转换,提升代码效率

修改后的代码

def update_data(n, val):  # input parameter(s)
    if n is None:
        return (
            "Hey there! Please enter a legitimate stock code to get details.",
            "https://melmagazine.com/wp-content/uploads/2019/07/Screen-Shot-2019-07-31-at-5.47.12-PM.png",
            "Stonks",
            None, None, None
        )
    else:
        if val is None:
            raise PreventUpdate
        else:
            ticker = yf.Ticker(val)
            inf = ticker.info
            # 安全获取字段,不存在则返回默认值
            logo_url = inf.get('logo_url', '')
            short_name = inf.get('shortName', 'Unknown Stock')
            business_summary = inf.get('longBusinessSummary', 'No business summary available.')
            return logo_url, short_name, business_summary, None, None, None

关键修改说明

  1. 用inf.get(key, default)替代直接访问字典键,确保字段不存在时不会报错,而是返回预设的默认值
  2. 移除了无意义的df[["logo_url", "shortName", "longBusinessSummary"]]代码行
  3. 把== None改成更规范的is None
  4. 直接操作字典,省去了DataFrame转换的步骤,代码更简洁高效

内容的提问来源于stack exchange,提问作者Suhail Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:32:49