Last active
July 12, 2020 01:26
-
-
Save x/7297b84cbd1762188bf35ece4ad6b332 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
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