Skip to content

Instantly share code, notes, and snippets.

@x
Last active July 12, 2020 01:26
Show Gist options
  • Save x/7297b84cbd1762188bf35ece4ad6b332 to your computer and use it in GitHub Desktop.
Save x/7297b84cbd1762188bf35ece4ad6b332 to your computer and use it in GitHub Desktop.
from typing import Any, List, Optional
def get_in(x: Any, ks: Optional[List[Any]], default: Any = None):
"""Recursively get nested values from dicts and lists in python.
A better alternative to .get(...) chains and safe for index errors on lists.
Example:
>>> get_in({"foo": ["a", {"bar": "b"}]}, ["foo", 1, "bar"])
"b"
>>> get_in([1, 2], [7], default="foo")
"foo"
"""
if not ks:
return x
try:
return get_in(x[ks[0]], ks[1:])
except (KeyError, IndexError):
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment