Better way to loop through nested categories?
<p>I have a sqlalchemy categories table that looks like this:</p>

<pre><code>id | parent_id | name
1 | 0 | license
2 | 1 | Digital Media
3 | 1 | Advertising
4 | 2 | Email Marketing
</code></pre>

<p>My goal is to convert this into a nested dictionary or list that I can loop through in a Flask template. The code below works but looks very messy to me. Is there a way I can improve it?</p>

<pre><code>categories = Category.query.all()
roots = [root for root in categories if root.parent_id == 1]
items = []
for root in roots:
    items.append({'root': root.name, 'subcategories': []})
    for category in categories:
        if category.parent_id == root.id:
            items[-1]['subcategories'].append(category.name) 
</code></pre>

<p>You can nest list comprehensions, so you need not double-loop through <code>roots</code> and <code>categories</code>.</p>

<pre><code>categories = Category.query.all()
roots = [root for root in categories if root.parent_id == 1]
items = [
    {
        'root': root.name,
        'subcategories': [
            category.name
            for category in categories
            if category.parent_id == root.id
        ]
    }
    for root in roots
]
</code></pre>

python