Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Last active May 26, 2022 12:23
Show Gist options
  • Save markscottwright/aae2dce03adbc3a6f281a5e394ad4cc0 to your computer and use it in GitHub Desktop.
Save markscottwright/aae2dce03adbc3a6f281a5e394ad4cc0 to your computer and use it in GitHub Desktop.
Python function to dig into a nested obect without errors
def get_value(o, *args, default=None):
for argIndex, arg in enumerate(args):
if isinstance(arg, int):
if isinstance(o, list) and 0 <= arg < len(o):
o = o[arg]
else:
return default
elif isinstance(arg, str):
if isinstance(o, dict) and arg in o:
o = o[arg]
else:
return default
else:
raise Exception(f"Arguments #{argIndex} ({arg}) not a string or integer")
return o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment