Skip to content

Instantly share code, notes, and snippets.

@neuman
Created April 25, 2012 15:57
Show Gist options
  • Save neuman/2490879 to your computer and use it in GitHub Desktop.
Save neuman/2490879 to your computer and use it in GitHub Desktop.
search nested lists of python objects (great for mongoengine)
def get_embedded(self, hierarchy, key, value, indexes=False):
"""get a list containing the ordered indexes of embedded documents.
A recursive depth first search replacing the nested for loops normally required
to iterate through nested objects contained within lists to find a single object
that has a specific value for a specific key.
Keyword Arguments:
hierarchy -- a list of keys needed to access the list containingthe next level of objects to search
key -- the string name of the member to match value too
value -- the value that key is being matched too
indent -- used to make the print easy to read
indexes -- if True, return a list of indexes ordered the same as the hierarchy,
useful for targeting/updating embedded mongo documents
"""
index = 0
domain = hierarchy.pop(0)
if len(hierarchy) == 0:
#if we're at the lowest level of the hierarchy, compare the key and value
for embedded in self[domain]:
if embedded[key] == value:
if indexes==True:
return [index]
else:
return embedded
index += 1
else:
for embedded in self[domain]:
#if the key and value matched at a lower level, add this level's index to the address list
output = embedded.get_embedded(hierarchy, key, value, indexes=indexes)
if output != None:
if indexes==True:
output.insert(0, index)
return output
else:
return output
index += 1
hierarchy.insert(0, domain)
return None
@neuman
Copy link
Author

neuman commented Apr 25, 2012

This is best used if included in a base class. I use it in the base class for my mongoengine documents, completely removing the need to write nested for loops to search for deeply embedded documents. This makes the db query vs in memory trade-off less painful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment