3

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.

Madhan Varadhodiyil
  • 2,086
  • 1
  • 14
  • 20
zerohedge
  • 3,185
  • 4
  • 28
  • 63

2 Answers2

4

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)...

Daniel Ong
  • 283
  • 1
  • 12
2

You can catch multiple exceptions in a single line;

final_dict["short_title"] = article_as_dict["short_title"]
try:
    final_dict["picture_url"] = article_as_dict["main_image"]["img"][-1]["link"]
except (IndexError, KeyError) as e:
    final_dict["picture_url"] = None
Madhan Varadhodiyil
  • 2,086
  • 1
  • 14
  • 20