Skip to content

Instantly share code, notes, and snippets.

@seanlinehan
Last active December 10, 2015 02:58
Show Gist options
  • Save seanlinehan/4371554 to your computer and use it in GitHub Desktop.
Save seanlinehan/4371554 to your computer and use it in GitHub Desktop.
Returns first occurrence of a key in a multidimensional object. If anybody has a more efficient method, tweet at me! @_slinehan
# Returns first occurrence of a key in a multidimensional object
# Haystack can either be a dict or a list, but needle must be
# a dict key name or a list of dict key names
# Example:
# deepObject = {
# 'Sky': {
# 'Planes': 2.5,
# 'Rockets': 3.5,
# 'Missiles': 3.0,
# 'Jets': [
# [1, 2, 3, 4, 5],
# [6, 7, 8, 9, 10],
# {
# 'Blue': 5,
# 'Green': 6,
# 'Purple': 7
# }
# ]
# }
# }
# deep_search('Blue', deepObject)
# returns: 5
def deep_search(needles, haystack):
## Build our return values
found = {}
## If we only passed one key, make it a list
if type(needles) != type([]):
needles = [needles]
## Search if haystack is a dictionary
if type(haystack) == type(dict()):
## Loop over each needle
for needle in needles:
if needle in haystack.keys():
found[needle] = haystack[needle]
elif len(haystack.keys()) > 0:
for key in haystack.keys():
result = deep_search(needle, haystack[key])
if result:
for k, v in result.items():
found[k] = v
elif type(haystack) == type([]):
for node in haystack:
result = deep_search(needles, node)
if result:
for k, v in result.items():
found[k] = v
return found
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment