Last active
October 28, 2020 19:31
-
-
Save jacobpledger/cb2e98df4896a030d6af8003a6c2afb3 to your computer and use it in GitHub Desktop.
Depth-first search in Python.
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
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