Skip to content

Instantly share code, notes, and snippets.

@neotheicebird
Last active November 20, 2016 18:57
Show Gist options
  • Save neotheicebird/954b13b8428fbc463890a67e14282290 to your computer and use it in GitHub Desktop.
Save neotheicebird/954b13b8428fbc463890a67e14282290 to your computer and use it in GitHub Desktop.
Get an item from a dictionary obtained from a JSON object obtained from a WEB API (not any JSON). Input: List of keys, e.g ["key_1", "key_2", 5, "key_4"]. Output: An item of type <str>, <list>, or<dict>
def get_from_json_dict(json_dict, keys, default_dict=None):
for index, key in enumerate(keys):
if isinstance(json_dict, dict) and isinstance(key, str): # check if you have a `dict` and `str` in hand
# get item of the key from json_dict, if key is Bad, get item from default_dict, or get None
json_dict = json_dict.get(key, default_dict[key] if default_dict else None)
if default_dict:
default_dict = default_dict[key] # reducing default dict
continue
if isinstance(json_dict, list) and isinstance(key, int): # check if you have a `list` and `int` in hand
# get item of the key (`int`) from json_dict (of type `list`), if key is Bad, get item from default_dict, or get None
try:
json_dict = json_dict[key]
except IndexError:
return default_dict[index] if default_dict else None
continue
return None
return json_dict # this now holds the final value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment