Last active
May 26, 2022 12:23
-
-
Save markscottwright/aae2dce03adbc3a6f281a5e394ad4cc0 to your computer and use it in GitHub Desktop.
Python function to dig into a nested obect without errors
This file contains hidden or 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
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