Last active
September 3, 2016 04:39
-
-
Save emmanuellyautomated/7405c0f186fe973ad9426b8b967519ba to your computer and use it in GitHub Desktop.
can determine if a search term is a value in a nested dictionary
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
def search_dict(d, term, nests=[]): | |
def last(array): | |
return array[-1] | |
''' | |
breadth-first search a dictionary | |
''' | |
presence = None | |
nests_at_this_level = [d.get(key) for key in d.keys() if type(d.get(key)).__name__ == 'dict'] | |
lists_with_nests = [d.get(key) for key in d.keys() | |
if type(d.get(key)).__name__ == 'list' | |
and any(filter(lambda x: type(x).__name__ == 'dict', d.get(key))) | |
] | |
nests_from_lists = [item for list_of_items in lists_with_nests for item in list_of_items] | |
nests_at_this_level.extend(nests_from_lists) | |
if nests_at_this_level: | |
nests.append(nests_at_this_level) | |
else: | |
for val in d.values(): | |
presence = True if term in val else None | |
if presence is not None: | |
return presence | |
if any(nests): | |
if any(last(nests)): | |
nest = last(nests).pop() | |
if last(nests)==[]: | |
nests.pop() | |
return search_dict(nest, term, nests) | |
else: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
...now for a 'monkey wrench'...