Last active
September 9, 2022 09:16
-
-
Save EnriqueSoria/8bf6f7c6637be2bb098b404a85b1ace2 to your computer and use it in GitHub Desktop.
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
import functools | |
from typing import Any | |
from operator import getitem | |
def get_from_path(data: dict, *path, default: Any = None) -> Any: | |
""" | |
Safe get data given a path returning a default value | |
>>> mydict = {"first": {"second": [3, 4]}} | |
>>> get_from_path(mydict, "first", default=0) | |
{'second': [3, 4]} | |
>>> get_from_path(mydict, "first", "second", 0, default=0) | |
3 | |
>>> get_from_path(mydict, "first", "second", 9, default=0) | |
0 | |
>>> get_from_path(mydict, "second", "first", default=0) | |
0 | |
>>> get_from_path(mydict, "first", "second", "third", default=0) | |
0 | |
>>> get_from_path([{"a": 42}], 0, "a") | |
42 | |
>>> get_from_path([{"a": 42}], 0, "error", default=1) | |
1 | |
""" | |
try: | |
return functools.reduce(getitem, path, data) | |
except (KeyError, TypeError, IndexError): | |
return default | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment