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

为什么Python中对API URI使用.format()方法会返回KeyError: 'ticker'报错?

错误原因

你在字符串模板中使用了命名占位符{ticker},但调用str.format()方法时仅传入了位置参数,Python无法找到与ticker名称匹配的参数值,因此抛出KeyError: 'ticker'。

修复方案

方案1:使用位置占位符

将字符串模板中的{ticker}改为无名称的{},匹配format()传入的第一个位置参数:

import json
from urllib.request import urlopen

ticker = '$SPY'
f = urlopen("https://api.pushshift.io/reddit/search/submission/?q={}&subreddit=wallstreetbets&metadata=true&size=0&after=1610928000&before=1613088000".format(ticker))
j = json.load(f)
j['metadata']['total_results']

方案2:显式传入命名参数

保留{ticker}命名占位符,调用format()时显式指定ticker参数名:

ticker = '$SPY'
f = urlopen("https://api.pushshift.io/reddit/search/submission/?q={ticker}&subreddit=wallstreetbets&metadata=true&size=0&after=1610928000&before=1613088000".format(ticker=ticker))

方案3:使用f-string(Python 3.6+ 推荐)

直接使用f-string语法,无需单独调用format()方法,写法更简洁:

ticker = '$SPY'
f = urlopen(f"https://api.pushshift.io/reddit/search/submission/?q={ticker}&subreddit=wallstreetbets&metadata=true&size=0&after=1610928000&before=1613088000")

遍历ticker列表的实现示例

将公共url模板抽离后循环调用即可,增加异常捕获避免单个ticker请求失败中断整个流程:

import json
from urllib.request import urlopen

ticker_list = ['$SPY', '$AAPL', '$TSLA', '$MSFT']
url_template = "https://api.pushshift.io/reddit/search/submission/?q={}&subreddit=wallstreetbets&metadata=true&size=0&after=1610928000&before=1613088000"

for ticker in ticker_list:
    try:
        f = urlopen(url_template.format(ticker))
        res = json.load(f)
        print(f"{ticker} 统计结果:{res['metadata']['total_results']}")
    except:
        print(f"{ticker} 请求失败,跳过")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:57:03