Skip to content

Instantly share code, notes, and snippets.

@WintersMichael
Last active December 9, 2020 22:45
Show Gist options
  • Save WintersMichael/03a842bc1e047c31d39e4ca40d6ad3b2 to your computer and use it in GitHub Desktop.
Save WintersMichael/03a842bc1e047c31d39e4ca40d6ad3b2 to your computer and use it in GitHub Desktop.
Python recursive search
# 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