stratify_by_parent
stratify_by_parent(items, parent_ids)
Convert flat TreeItem data with parent-child relationships to hierarchical structure.
Takes a list of TreeItem objects where parent-child relationships are expressed through a separate list of parent_ids, and returns tree data where the parent-child relationships are expressed through the TreeItem children attribute.
This function preserves all fields and attributes from the original TreeItem objects, including any additional fields that may be added in future versions or custom extensions.
Parameters
items :
list
[TreeItem]-
List of TreeItem objects with empty children lists
parent_ids :
list
[Optional
[str
]]-
List of parent IDs corresponding to each TreeItem. None indicates a root item. Must be the same length as items list.
Returns
:
list
[TreeItem]-
List of root TreeItem objects with populated children attributes. All original fields and attributes are preserved.
Raises
:
ValueError
-
If items and parent_ids lists have different lengths If a parent_id references a non-existent item If circular references are detected
Example
from shiny_treeview import TreeItem, stratify_by_parent
# Flat data with parent-child relationships
= [
items id="root", label="Root"),
TreeItem(id="child1", label="Child 1"),
TreeItem(id="child2", label="Child 2"),
TreeItem(id="grandchild", label="Grandchild")
TreeItem(
]= [None, "root", "root", "child1"]
parent_ids
# Convert to hierarchical structure
= stratify_by_parent(items, parent_ids)
tree # Result: root item with child1 and child2 as children,
# and grandchild as a child of child1