Skip to content

Instantly share code, notes, and snippets.

@travishathaway
Last active August 29, 2015 14:08
Show Gist options
  • Save travishathaway/4d439c9e52863ba643e9 to your computer and use it in GitHub Desktop.
Save travishathaway/4d439c9e52863ba643e9 to your computer and use it in GitHub Desktop.
Recently, I had a problem. I only had a list of child to parent relations. I needed to create a nested list structure. This is how I did it.
import collections
def create_tree(edges):
'''
This parses the edges and creates a nested dictionary
'''
trees = collections.defaultdict(dict)
for child, parent in edges:
trees[parent][child] = trees[child]
children, parents = zip(*edges)
roots = set(parents).difference(children)
return {root: trees[root] for root in roots}
def nested_list(tree, n_list=[], level=0):
'''
This is where we create our nested list. It's a recursive function.
'''
for key, value in tree.items():
idx = len(n_list)
n_list.append(
{'id': key, 'nodes': []}
)
nested_list(
value, n_list=n_list[idx]['nodes'], level=level + 1
)
return n_list
def main():
# Test edges
edges = [(1, 2), (2, 3), (1, 3), (9, 12), (1, 12)]
# Create the nested tree
tree = create_tree(edges)
# Now create the nest list
n_list = nested_list(tree)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment