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

Python循环跳过字典null值报TypeError: unhashable type: 'dict'如何解决

报错原因与修复方案

错误原因

你遇到的TypeError: unhashable type: 'dict'错误由错误的取值逻辑引发:

  • prints.json()['data']是字典组成的列表,for i in prints.json()['data']中遍历得到的i本身就是单条卡牌数据的字典,不是可用于取值的索引/键名
  • 代码中prints.json()[i]尝试把字典i作为键名去取prints.json()的对应值,而字典属于不可哈希类型,无法作为字典的键,因此触发类型报错

另外还有两处需要修正的逻辑问题:

  • 不要在循环中重复调用prints.json(),重复解析响应会额外消耗性能,提前把解析结果存入变量即可
  • 该接口返回的空价格为None类型,不是字符串"null",判断条件需要对应调整

修正后代码

card = requests.get('https://api.scryfall.com/cards/named?fuzzy=' + search)
# 提前解析并存储接口返回结果
card_info = card.json()
prints_resp = requests.get(card_info['prints_search_uri'])
card_print_list = prints_resp.json()['data']

for card_item in card_print_list:
    usd_price = card_item['prices']['usd']
    # 空价格判断逻辑修正
    if usd_price is None:
        continue
    print(card_item['set_name'] + ': ' + usd_price)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:02