DataTree to List of Lists (Python)

I’m confused on how the ghpythonlib.treehelpers module is supposed to work.
I’m expecting the following code to convert the datatree in to a list of lists but instead it seems to only convert the first branch into a list and then stops. I’m suspecting you have to iterate through the branches but I’m unclear on how this is achieved.

import ghpythonlib.treehelpers as th
MyDataTree = x
a = th.tree_to_list(MyDataTree)
print(a)

1 Like

I agree this doesn’t make sense. tree_to_list takes a second argument. I can’t remember the format, but I think it should be tree_to_list(MyDataTree, “[0;0]”)

This should help

Edit: syntax for source argument is here
layerTree = th.list_to_tree(layerTree, source=[0,0])

Couldn’t figure out if that second argument was necessary or not but my problem seemed to be that I simplified the input from {0, 0} to {0}. Un-simplifying the data tree fixed the issue. Not sure exactly why this is though.

Hi @Ryan_Whitby,

Some time ago, I found this Python method on GitHub:

# written by Giulio Piacentino, giulio@mcneel.com
def tree_to_list(input, retrieve_base = lambda x: x[0]):
    """Returns a list representation of a Grasshopper DataTree"""
    def extend_at(path, index, simple_input, rest_list):
        target = path[index]
        if len(rest_list) <= target: rest_list.extend([None]*(target-len(rest_list)+1))
        if index == path.Length - 1:
            rest_list[target] = list(simple_input)
        else:
            if rest_list[target] is None: rest_list[target] = []
            extend_at(path, index+1, simple_input, rest_list[target])
    all = []
    for i in range(input.BranchCount):
        path = input.Path(i)
        extend_at(path, 0, input.Branch(path), all)
    return retrieve_base(all)

It works great for most trees, in my experience.

1 Like

Did anyone ever find the cause of this issue?