Skip to content

Instantly share code, notes, and snippets.

@zpconn
Created January 13, 2014 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zpconn/8394706 to your computer and use it in GitHub Desktop.
Save zpconn/8394706 to your computer and use it in GitHub Desktop.
Given a list of pairs, each containing the name of a node and the name of its parent, respectively, this builds the full tree as a nested dictionary. Note that the parent of the root node is specified by None.
def build(pairs, root=None):
tree = {}
for (child, parent) in pairs:
if parent == root:
tree[child] = build(filter(lambda x: x != (child, parent), pairs), child)
return tree
print build([("H", "G"), ("F", "G"), ("G", "D"), ("E", "D"), ("A", "E"), ("B", "C"), ("C", "E"), ("D", None)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment