Created
January 22, 2020 11:53
-
-
Save AdamSpannbauer/e73937864d50da900f11ea635b8e0802 to your computer and use it in GitHub Desktop.
Example for default dict to handle missing keys.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
import numpy as np | |
def api_call(response_ok=True): | |
if response_ok: | |
return {'Released': 2010, 'Ratings': [{'Value': 98}]} | |
else: | |
return defaultdict(lambda: np.nan) | |
# Pretend to have bad API response | |
extra_info_ok = api_call(True) | |
extra_info_not_ok = api_call(False) | |
print(extra_info_ok['Released']) # Output: 2010 | |
print(extra_info_not_ok['Released']) # Output: np.nan | |
print(extra_info_ok['Ratings'][0]['Value']) # Output: 98 | |
print(extra_info_not_ok['Ratings'][0]['Value']) # Output: TypeError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment