[英]is there a better or more elegant way to handling dictionary loop exception in python?
基本上我只是解析一個JSON文件,其中包含有關幾部電影的信息,並將其中的一些保存在不同的字典中供以后使用
例如:並非所有電影都有描述,我正在使用try / except來處理當json中沒有描述時出現的“keyError”,有沒有更好的方法呢?
for movie in json:
# other entries
try:
description = {"description": movie_details['Description']}
except KeyError:
description = {"description": ""}
# other entries
try:
other_value = {"other_value": movie_details["other_value"]
except KeyError:
other_value = {"other_value": ""}
這對我來說非常“骯臟”,如果你有一些提示寫一個更干凈的代碼會很棒
謝謝
一種方法是使用帶有sentinal值的.get()
:
for movie in json:
description = {'description': movie_details.get('Description', '')}
# and similarly for other values...
這可確保如果未找到密鑰,則使用sentinal值。
我不確定你是否需要在循環中使用movie_details
或movie
。 我想你的意思是后者。
一種方法是將movie_details
轉換為collections.defaultdict
movie_details = collections.defaultdict(str,movie_details)
如果找不到某個鍵,專用字典對象會調用str
來創建一個新鍵(空字符串)
完成此操作后,只需像普通的dict訪問一樣使用它:
description = {'description': movie_details['Description']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.