python - 我正在尝试制作一个程序来显示美元价值,但我无法让它向我打印我想要的信息
问题描述
所以,这是脚本。我正在使用我在互联网上找到的这个 api,它可以工作,但是当我试图让它只打印我想要的信息时,会出现以下错误:
Traceback (most recent call last):
File "c:/Users/perei/OneDrive/Documentos/Evylla/python/projetos python/cotacao_dolar.py", line 13, in <module>
print("Moeda estrangeira: {}".format(dolar_cot["code"]))
KeyError: 'code'
import requests
import json
dolar = requests.get("https://economia.awesomeapi.com.br/all/USD-BRL")
dolar_cot = dolar.json()
# print(dolar.text)
if "status" == 404:
print("Moeda não encontrada")
else:
print("")
print("Moeda estrangeira: {}".format(dolar_cot["code"]))
print("Moeda nacional: {}".format(dolar_cot["codein"]))
print("Moeda estrangeira: {}".format(dolar_cot["code"]))
print("Momento mais baixo: {}".format(dolar_cot["low"]))
print("Moeda mais alto: {}".format(dolar_cot["high"]))
print("Oferta: {}".format(dolar_cot["bid"]))
print("Pedido: {}".format(dolar_cot["ask"]))
解决方案
这是您向 API 发送获取请求时的响应
{"USD":{
"code":"USD",
"codein":"BRL","name":"Dólar Comercial",
"high":"5.327",
"low":"5.2477",
"varBid":"0.0104",
"pctChange":"0.2",
"bid":"5.3003",
"ask":"5.3033",
"timestamp":"1599253196",
"create_date":"2020-09-04 21:00:01"}
}
如您所见,所有字段都嵌套在"USD"
. 所以只需更改dolar_cot = dolar.json()
为dolar_cot = dolar.json()["USD"]
推荐阅读
- sql - SQL如何设置一个空值来替换另一个字符
- java - 从路径变量中检索数据并插入模型
- mysql - mysql将完整的行数据从一个表复制到另一个具有不同字段的表
- html - 菜单在移动浏览器桌面站点视图中不可见
- javascript - 从科尔多瓦钩子中读取环境变量
- reactjs - React、Typescipt、条件 rops
- r - 如何停止键盘模拟器?
- promtail - 事件路由器事件的 Promtail 正则表达式问题
- swift - 状态栏颜色:preferredStatusBarStyle 与 childViewControllerForStatusBarStyle
- java - java - 如何在java spring boot中从另一个数据库表中获取实体列表?