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

调用Rest Countries API时,函数中字典存在INR键却触发KeyError

解决Rest Countries API调用时的KeyError: 'INR'问题

我尝试调用Rest Countries API获取印度的相关信息,代码如下:

def country():
  country_url= 'https://restcountries.com/v3.1/name/india'
  request = urllib.request.urlopen(country_url)
  result = json.loads(request.read())
  for values in result:
    print(values['currencies'])
    indian_currency= values['currencies']['INR']['name']    
    capital= values["capital"]
    for capital in values["capital"]:
      capital_city=capital
      continent= values["region"]
    
    print(f"The currency of India is the {indian_currency}, the capital city is {capital_city} and it is in the continent of {continent}.")

运行时报错:

Traceback (most recent call last):
  File "main.py", line 19, in <module>
    country()
  File "main.py", line 11, in country
    indian_currency= values['currencies']['INR']['name']    
    KeyError: 'INR'

我发现indian_currency变量能在格式化字符串中正常输出对应值,但仍然触发了KeyError: 'INR',且已确认该键存在,无法理解问题所在。


问题原因

调用https://restcountries.com/v3.1/name/india返回的结果不止一个条目,其中第一个条目是印度主数据(包含INR键),但后续条目(比如印度的海外领地或别名对应的数据)的currencies字段里没有INR键。你看到indian_currency能输出是因为第一个循环迭代成功执行并打印了内容,但循环到后续条目时就触发了KeyError。

解决方案

方案1:精确匹配单个结果

在请求URL后添加?fullText=true参数,强制API返回完全匹配"india"的条目,确保只获取印度主数据:

import urllib.request
import json

def country():
  # 添加fullText=true参数精确匹配
  country_url= 'https://restcountries.com/v3.1/name/india?fullText=true'
  request = urllib.request.urlopen(country_url)
  result = json.loads(request.read())
  # 因为只返回一个结果,直接取第一个元素,不需要循环
  values = result[0]
  print(values['currencies'])
  indian_currency= values['currencies']['INR']['name']    
  # 印度首都列表只有一个元素,直接取第一个即可,无需循环
  capital_city = values["capital"][0]
  continent= values["region"]
    
  print(f"The currency of India is the {indian_currency}, the capital city is {capital_city} and it is in the continent of {continent}.")

方案2:添加键存在性检查

如果需要保留循环处理多个结果的逻辑,在访问INR键前先检查是否存在,避免报错:

import urllib.request
import json

def country():
  country_url= 'https://restcountries.com/v3.1/name/india'
  request = urllib.request.urlopen(country_url)
  result = json.loads(request.read())
  for values in result:
    print(values['currencies'])
    # 先检查INR是否存在
    if 'INR' in values.get('currencies', {}):
      indian_currency= values['currencies']['INR']['name']    
      capital_city = values["capital"][0] if values.get("capital") else "Unknown"
      continent= values.get("region", "Unknown")
      print(f"The currency of India is the {indian_currency}, the capital city is {capital_city} and it is in the continent of {continent}.")
    else:
      print(f"This entry doesn't have INR currency: {values.get('name', {}).get('common', 'Unknown')}")

额外优化点

  • 代码中原本的capital循环完全没必要,印度的首都列表只有一个元素,直接通过values["capital"][0]获取即可。
  • 使用dict.get()方法访问键可以避免KeyError,比如values.get('capital', []),即使键不存在也不会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:40:29