Loop through categories recursively
<p>I'm building a python function which returns an array to be used in a select dropdown field. I have tried two versions so far. </p>

<p>Both of them work, with the first returning a properly formatted select field. However, the first solution only goes two levels deep. I intend to add more depth to the categories. </p>

<p>My second example is my attempt at doing this recursively to support more levels. It works but I'm wondering how I can optimize it and add dashes similar to the first example.</p>

<pre><code># first example two levels deep, formatted properly with dashes
def build_choice_tree():
    categories = Category.query.get(1).children
    items = [(1, 'None')]
    for root in categories:
        items.append((root.id, root.name))
        if root.children:
            for subcat1 in root.children:
                items.append((subcat1.id, '- ' + subcat1.name))
                if subcat1.children:
                    for subcat2 in subcat1.children:
                        items.append((subcat2.id, '--' + subcat2.name))
    return items

# second example goes multiple levels, needs dashes
def build_choice_tree2():
    categories = Category.query.get(1).children
    items = []

    def loop(categories):
        for category in categories:
            items.append((category.id, category.name))
            if category.children:
                loop(category.children)
        return items
    result = loop(categories)
    return result
</code></pre>

<p>I change you example 2, and it will add dashes after the id, but it won't add spaces like your example 1.</p>

<pre><code># second example goes multiple levels, needs dashes
def build_choice_tree2():
    # For the convenience of the test, I changed `categories` to a list.
    categories = [{
        'id': 1,
        'name': 'root',
        'children': [{
            'id': 2,
            'name': 'child1',
            'children': [{
                'id': 3,
                'name': 'child2',
            }]
        }]
    }]
    items = []
    def loop(categories, depth):
        for category in categories:
            items.append((category['id'], '-' * depth + ' ' + category['name']))
            if category.get('children'):
                loop(category['children'], depth + 1)
        return items
    result = loop(categories, 0)
    print(result)
    return result

if __name__ == '__main__':
    build_choice_tree2()
</code></pre>

python recursion