在我的货币转换器中出现“KeyError”

问题描述

我正在尝试制作货币转换器,但出现此错误,原因是什么?

我正在使用 alphavantage 来获取值。

import requests,json 

def AlPHPaFetcher(from_currency,to_currency,api_key): 
    alpha_url = r"https://www.alphavantage.co/query?function = CURRENCY_EXCHANGE_RATE"
    final_url = alpha_url + "&from_currency =" + from_currency + "&to_currency =" + to_currency + "&apikey =" + api_key 
    req_ob = requests.get(final_url) 
    result = req_ob.json() 
    
    print("Realtime Currency Exchange Rate for",result["Realtime Currency Exchange Rate"] 
                ["2. From_Currency Name"],"TO",result["Realtime Currency Exchange Rate"] 
                ["4. To_Currency Name"],"is",result["Realtime Currency Exchange Rate"] 
                ['5. Exchange Rate'],to_currency) 

if __name__ == "__main__" :
    from_currency = "USD"
    to_currency = "BRL"    
    api_key = "XXXXXXXXXX"
    AlPHPaFetcher(from_currency,api_key)

并返回这个

Traceback (most recent call last):
  File "c:\Users\Lucas\Desktop\teste.py",line 37,in <module>
    AlPHPaFetcher(from_currency,api_key)
  File "c:\Users\Lucas\Desktop\teste.py",line 19,in AlPHPaFetcher
    result["Realtime Currency Exchange Rate"] 
KeyError: 'Realtime Currency Exchange Rate'

解决方法

更正您的网址结构:(注意 = 前没有空格)

    alpha_url = r"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE"

    final_url = alpha_url + "&from_currency=" + from_currency + "&to_currency=" + to_currency + "&apikey=" + api_key 
    req_ob = requests.get(final_url)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...