Skip to content

Instantly share code, notes, and snippets.

@EnriqueSoria
Last active September 9, 2022 09:16
Show Gist options
  • Save EnriqueSoria/8bf6f7c6637be2bb098b404a85b1ace2 to your computer and use it in GitHub Desktop.
Save EnriqueSoria/8bf6f7c6637be2bb098b404a85b1ace2 to your computer and use it in GitHub Desktop.
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