treevalue.utils.tree

build_tree

treevalue.utils.tree.build_tree(root, represent=None, iterate=None, recurse=None) → treelib.tree.Tree[source]
Overview:

Build a treelib object by an object.

Arguments:
  • root (Any): Root object.

  • represent (Optional[Callable]): Represent function, default is primitive repr.

  • iterate (Optional[Callable]): Iterate function, default is lambda x: x.items().

  • recurse (Optional[Callable]): Recurse check function, default is lambda x: hasattr(x, ‘items’).

Returns:
  • tree (treelib.Tree): Built tree.

Example:
>>> t = build_tree(
>>>     {'a': 1, 'b': 2, 'x': {'c': 3, 'd': 4}, 'z': [1, 2], 'v': {'1': '2'}},
>>>     represent=lambda x: '<node>' if isinstance(x, dict) else repr(x),
>>>     recurse=lambda x: isinstance(x, dict),
>>> )
>>> print(t)

The output should be

>>> <node>
>>> ├── 'a' --> 1
>>> ├── 'b' --> 2
>>> ├── 'v' --> <node>
>>> │   └── '1' --> '2'
>>> ├── 'x' --> <node>
>>> │   ├── 'c' --> 3
>>> │   └── 'd' --> 4
>>> └── 'z' --> [1, 2]