fork download
  1. import json
  2.  
  3.  
  4. def attach_branch(tree, branch):
  5. l = len(branch)
  6. node = branch[0]
  7. # If node doesn't exist get an empty subtree
  8. subtree = tree.get(node, {})
  9.  
  10. if l == 1:
  11. # Create leaf node
  12. tree.update({node: subtree})
  13. return tree
  14.  
  15. subtree.update(attach_branch(subtree, branch[1:]))
  16.  
  17. tree.update({node: subtree})
  18. return tree
  19.  
  20.  
  21. if __name__ == '__main__':
  22. root_list = []
  23. tree = {}
  24.  
  25. prefixes = [
  26. 'F',
  27. 'A|B|C',
  28. 'A|B|D',
  29. 'B|C|D',
  30. 'B|C|E',
  31. 'A',
  32. ]
  33.  
  34. for branch in map(lambda x: x.split('|'), prefixes):
  35. if len(branch) == 1:
  36. root_list.append(branch[0])
  37. continue
  38.  
  39. tree = attach_branch(tree, branch)
  40.  
  41. root_list.append(tree)
  42. print(json.dumps(root_list, indent=2))
Success #stdin #stdout 0.02s 30200KB
stdin
Standard input is empty
stdout
[
  "F",
  "A",
  {
    "A": {
      "B": {
        "C": {},
        "D": {}
      }
    },
    "B": {
      "C": {
        "D": {},
        "E": {}
      }
    }
  }
]