我對 Python 還很陌生,所以請耐心等待。我有一個函式需要兩個引數,一個 api 回應和一個輸出物件,我需要將一些值從 api 回應分配給輸出物件:
def map_data(output, response):
try:
output['car']['name'] = response['name']
output['car']['color'] = response['color']
output['car']['date'] = response['date']
#other mapping
.
.
.
.
#other mapping
except KeyError as e:
logging.error("Key Missing in api Response: %s", str(e))
pass
return output
現在有時,api 回應缺少一些我用來生成輸出物件的鍵,所以我使用 KeyError 例外來處理這種情況。
現在我的問題是,在 api 回應中缺少“顏色”鍵的情況下,我如何捕獲例外并繼續執行它output['car']['date'] = response['date']和其余指令之后的行。
我嘗試了pass說明,但沒有任何影響。
Ps:我知道我可以使用以下方法檢查密鑰是否存在:
if response.get('color') is not None:
output['car']['color'] = response['color']
然后分配值,但看到我需要映射大約 30 個值,還有其他方法可以實作嗎?謝謝
uj5u.com熱心網友回復:
一些直接的想法
(僅供參考 - 我不會詳細解釋所有內容 - 您可以查看 Python 檔案以獲取更多資訊、示例等 - 這將幫助您了解更多資訊,而不是試圖在這里解釋所有內容)
一百萬種方法/想法/方法的谷歌“python處理字典丟失的鍵”——這是一個常見的用例!
將您的回應 dict 轉換為
defaultdict. 在這種情況下,如果沒有回傳實際值,您可以回傳一個默認值(例如 None、''、'N/A'...任何您喜歡的)。
在這種情況下,您可以取消try并且每一行都將被執行。
from collections import defaultdict
resp=defaultdict(lambda: 'NA', response)
output['car']['date'] = response['date'] # will have value 'NA' if 'date' isnt in response
- 使用
in語法,也許結合三元else
output['car']['color'] = response['color'] if 'color' in response
output['car']['date'] = response['date'] if 'date' in response else 'NA'
同樣,您可以取消 try 塊,并且每一行都將執行。
- 使用字典
get函式,如果該鍵沒有值,它允許您指定默認值:
output['car']['color'] = response.get('car', 'no car specified')
uj5u.com熱心網友回復:
您可以創建一個從回應中獲取值的實用函式,如果未找到該值,它將回傳一個空字串。請參閱下面的示例:
def get_value_from_response_or_null(response, key):
try:
value = response[key]
return value
except KeyError as e:
logging.error("Key Missing in api Response: %s", str(e))
return ""
def map_data(output, response):
output['car']['name'] = get_value_from_response_or_null(response, 'name')
output['car']['color'] = get_value_from_response_or_null(response, 'color')
output['car']['date'] = get_value_from_response_or_null(response, 'date')
# other mapping
# other mapping
return output
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350362.html
