Skip to content

Instantly share code, notes, and snippets.

@jacobpledger
Last active October 28, 2020 19:31
Show Gist options
  • Save jacobpledger/cb2e98df4896a030d6af8003a6c2afb3 to your computer and use it in GitHub Desktop.
Save jacobpledger/cb2e98df4896a030d6af8003a6c2afb3 to your computer and use it in GitHub Desktop.
Depth-first search in Python.
from typing import Any
def dfs(haystack: dict, needle: Any) -> Any:
"""
Depth-first search in a dict for the specified key, for which the
value is returned.
:param haystack: The dictionary we want to search.
:param needle: the key, whose value we are searching for
:return: the value at the given key or None if not found.
"""
value = None
for k, v in haystack.items():
if isinstance(v, dict):
return dfs(haystack=v, needle=k)
if needle in haystack:
value = haystack[needle]
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment