Skip to content

Instantly share code, notes, and snippets.

@jacobpledger
Created October 28, 2020 19:31
Show Gist options
  • Save jacobpledger/b0a016db141686ffe55d4d2e7c13a9b0 to your computer and use it in GitHub Desktop.
Save jacobpledger/b0a016db141686ffe55d4d2e7c13a9b0 to your computer and use it in GitHub Desktop.
Breadth-first search in Python.
from typing import Any
def bfs(haystack: dict, needle: Any) -> Any:
"""
Breadth-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.
"""
if needle in haystack:
return haystack[needle]
value = None
for k, v in haystack.items():
if isinstance(v, dict):
value = bfs(haystack=v, needle=k)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment