Last active
December 9, 2020 22:45
-
-
Save WintersMichael/03a842bc1e047c31d39e4ca40d6ad3b2 to your computer and use it in GitHub Desktop.
Python recursive search
This file contains 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
# Recursively searches a Python object (composed of both dicts and lists) to find all items with key name `key` | |
def finditems(obj, key, results: list = None) -> list: | |
if results is None: | |
# this is the outermost function call, so init storage for all recursive calls | |
results = [] | |
if isinstance(obj, dict): | |
if key in obj: | |
results.append(obj[key]) | |
# recurse through dict | |
for k, v in obj.items(): | |
if isinstance(v, dict) or isinstance(v, list): | |
finditem(v, key, results) | |
elif isinstance(obj, list): | |
if key in obj: | |
results.append(obj) | |
# recurse through list | |
for v in obj: | |
if isinstance(v, dict) or isinstance(v, list): | |
finditem(v, key, results) | |
return results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment