python 尝试除了误用 - 我应该用什么代替?

问题描述 投票:0回答:1

我正在使用外部 API 并尝试将其中的数据自动输入到我自己的应用程序中。 假设我正在进行的 API 调用始终具有“长度”和“周长”字段,有时具有“颜色”字段。

我目前设置的从API调用中提取数据的方式是这样的:

蟒蛇

resp = request.get(some_api_call)

length = resp.json()['length']
girth = resp.json()['girth']
try:
   colour = resp.json()['colour']
except:
   colour = 'unknown'

# do something with data all three variables.

我的问题是我应该如何在不使用 try 和 except 的情况下执行此操作?我确信我没有按照预期使用它,我想确保高质量的代码。

python try-except
1个回答
0
投票

Python dictionary 类型有一个名为

get
的方法,如果键不存在,您可以在其中指定默认值。

resp = request.get(some_api_call)

length = resp.json()['length']
girth = resp.json()['girth']
colour = resp.json().get('colour','unknown')
© www.soinside.com 2019 - 2024. All rights reserved.