Skip to content

Instantly share code, notes, and snippets.

@theelous3
Last active May 14, 2018 13:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save theelous3/e42c69ae1d47297cee14a8a478052750 to your computer and use it in GitHub Desktop.
test = {
'lol': ['wat', 'the', 'fuck'],
'ten': 'pence',
'who': {'did': 1, 'the': 2, 'poop': 3},
'this': [{'goes': {'pretty': 'deep'}, 'if': {'I': 'may say so'}}]
}
class StopSearch(Exception):
pass
def traverse(obj, key):
if isinstance(obj, dict):
if key in obj:
raise StopSearch(key)
return {k: traverse(v, key) for k, v in obj.items()}
elif isinstance(obj, list):
return [traverse(elem, key) for elem in obj]
else:
return obj
def find_traverse(target, key):
try:
traverse(target, key)
except StopSearch:
return True
return False
find_traverse(test, 'pretty')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment