Last active
August 29, 2015 14:08
-
-
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.
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
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