I have the following piece of code. article_as_dict is a dictionary that I'm receiving from an external source:
final_dict["short_title"] = article_as_dict["short_title"]
try:
final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"]
except IndexError:
final_dict["picture_url"] = None
I discovered recently that I also need to account for a possible KeyError, is the block below the most pythonic way to do this?
final_dict["short_title"] = article_as_dict["short_title"]
try:
final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"]
except IndexError:
final_dict["picture_url"] = None
except KeyError:
final_dict["picture_url"] = None
I don't want a naked except clause because it's bad practice.
You can catch multiple types of errors in one line.
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple
It would be more pythonic to catch your errors like so:
except (IndexError, KeyError)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With