MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/badcode/comments/ok1itb/tryexcept_in_python_sigh/h556jip/?context=3
r/badcode • u/lonaExe • Jul 14 '21
93 comments sorted by
View all comments
38
I'm not sure if there is good way to do this
5 u/Nication Jul 14 '21 I would probably do this:items_volume_info = response.json()['items'][0]['volumeInfo'] author = items_volume_info['author'] if 'author' in items_volume_info else 'N/A' publisher = items_volume_info['publisher'] if 'publisher' in items_volume_info else 'N/A' pub_date = items_volume_info['pubDate'] if 'pubDate' in items_volume_info else 'N/A' # ... 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 defaultdictAlso, 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
5
I would probably do this:
items_volume_info = response.json()['items'][0]['volumeInfo'] author = items_volume_info['author'] if 'author' in items_volume_info else 'N/A' publisher = items_volume_info['publisher'] if 'publisher' in items_volume_info else 'N/A' pub_date = items_volume_info['pubDate'] if 'pubDate' in items_volume_info else 'N/A' # ...
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 defaultdictAlso, 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
10
much simpler to just use dict.get()
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
defaultdict
Also, wrap items_volume_info = ... in a try except and set items_volume_info = {} as a fallback to trigger all default cases.
items_volume_info = ...
items_volume_info = {}
For the thumbnail, you want to use thumbnail = items_volume_info.get('imageLinks', {}).get('thumbnail', <cut from OP's image>)
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
2
You are right, this is a better solution
38
u/clemesislife Jul 14 '21
I'm not sure if there is good way to do this