Created
August 15, 2025 21:18
-
-
Save Davis-3450/facbc2bbfa68cc6c19f825438b285f4d to your computer and use it in GitHub Desktop.
DSA snippets
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 dfs(obj, key) -> dict | list | None: | |
| """ | |
| Finds an item and returns values | |
| Args: | |
| obj (dict | list): object | |
| key (str): target key | |
| Returns: | |
| dict | list | None | |
| """ | |
| # Handle dicts | |
| if isinstance(obj, dict): | |
| if key in obj: | |
| return obj[key] | |
| for v in obj.values(): | |
| r = dfs(v, key) | |
| if r is not None: | |
| return r | |
| # Handle lists and tuples | |
| elif isinstance(obj, (list, tuple)): | |
| for v in obj: | |
| r = dfs(v, key) | |
| if r is not None: | |
| return r | |
| return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DFS for returning the items of a key if it exists