Last active
December 14, 2023 10:32
-
-
Save nomtrosk/02670e3dfd7b2a46b139a10cd6227f72 to your computer and use it in GitHub Desktop.
Get element safely from nested dict
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
| def deep_get(data:dict[str,Any], keys:list[str]): | |
| try: | |
| key = keys[0] | |
| except IndexError: | |
| return data | |
| try: | |
| return deep_get(data[key], keys[1:]) | |
| except (KeyError,TypeError): | |
| return None | |
| data = {"a": {"b": 2}, "c": None} | |
| assert deep_get(data, ["a", "b"]) == 2 | |
| assert deep_get(data, ["a", "x"]) == None | |
| assert deep_get(data, ["x", "x"]) == None | |
| assert deep_get(data, ["c", "x"]) == None | |
| assert deep_get(data, ["a"]) == {"b": 2} | |
| assert deep_get(data, []) == data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment