To generate a Table of Content, I have these data available 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’d like to obtain this kind of nested structure, much more compatible with the use of a 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: []},
]
Hints on how to achieve this? I tried with a recursive function but it’s getting much tricky for my limited brain.
Any help much appreciated.
EDIT: Added fact that a section entry can have eventually no child. Sorry for the miss.
Assuming chapters come in order, meaning child chapter is always after the parent, and there are no missing parent (skipped levels):
Result:
EDIT: changed it to have empty ‘sub’ items where there are no children. See the other variant in edit history.