To create a table of contents, I have this data in a Python list:
data = [
{title: 'Section 1', level: 1, page_number: 1},
{title: 'Section 1.1', level: 2, page_number: 2},
{title: 'Section 1.2', level: 2, page_number: 3},
{title: 'Section 2', level: 1, page_number: 4},
{title: 'Section 2.1', level: 2, page_number: 5},
{title: 'Section 3', level: 1, page_number: 6},
]
From this, I would like to get such a nested structure that is much more compatible using the template engine:
toc = [
{title: 'Section 1', page_number: 1, sub: [
{title: 'Section 1.1', page_number: 2, sub: []},
{title: 'Section 1.2', page_number: 3, sub: []},
]},
{title: 'Section 2', page_number: 4, sub: [
{title: 'Section 2.1', page_number: 5, sub: []},
]},
{title: 'Section 3', page_number: 6, sub: []},
]
Tips on how to achieve this? I tried with recursive function, but it became very difficult for my limited brain.
Any help is greatly appreciated.
EDIT: Added the fact that in the section entry there can ultimately be no child. Sorry for the miss.