r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

Show parent comment

10

u/RoLoLoLoLo Jul 14 '21

much simpler to just use dict.get()

author = items_volume_info.get('author', 'N/A')

And if you have a lot of 'N/A' default values, go a step further and use defaultdict

Also, wrap items_volume_info = ... in a try except and set items_volume_info = {} as a fallback to trigger all default cases.

For the thumbnail, you want to use thumbnail = items_volume_info.get('imageLinks', {}).get('thumbnail', <cut from OP's image>)

2

u/Nication Jul 14 '21

You are right, this is a better solution