Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created March 8, 2022 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/5698d55c629a54e19d7394e051b3320f to your computer and use it in GitHub Desktop.
Save malcolmgreaves/5698d55c629a54e19d7394e051b3320f to your computer and use it in GitHub Desktop.
Function to support recursively accessing key-value pairs from a nested dictionary.
from typing import Any, Dict, Optional
def access(d: Dict[str, Any], *keys) -> Optional[Any]:
return reduce(dict.get, keys, d)
#
# Use as:
# >>>> access({"hello": {"world": {"how": "are you today?"}}}, "hello")
# >>>> access({"hello": {"world": {"how": "are you today?"}}}, "hello", "world")
# >>>> access({"hello": {"world": {"how": "are you today?"}}}, "hello", "world", "how")
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment