Skip to content

Instantly share code, notes, and snippets.

@Davis-3450
Created August 15, 2025 21:18
Show Gist options
  • Save Davis-3450/facbc2bbfa68cc6c19f825438b285f4d to your computer and use it in GitHub Desktop.
Save Davis-3450/facbc2bbfa68cc6c19f825438b285f4d to your computer and use it in GitHub Desktop.
DSA snippets
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
@Davis-3450
Copy link
Author

DFS for returning the items of a key if it exists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment