@@ -150,7 +150,7 @@ def _recursive_append(_node: T, parent_dict: Dict[str, Any]) -> None:
150150
151151def tree_to_nested_dict_key (
152152 tree : T ,
153- child_key : str = "children" ,
153+ child_key : Optional [ str ] = "children" ,
154154 attr_dict : Optional [Dict [str , str ]] = None ,
155155 all_attrs : bool = False ,
156156 max_depth : int = 0 ,
@@ -160,6 +160,7 @@ def tree_to_nested_dict_key(
160160 All descendants from `tree` will be exported, `tree` can be the root node or child node of tree.
161161
162162 Exported dictionary will have key as node names, and children as node attributes and nested recursive dictionary.
163+ If child_key is None, the children key is nested recursive dictionary of node names (there will be no attributes).
163164
164165 Examples:
165166 >>> from bigtree import Node, tree_to_nested_dict_key
@@ -171,6 +172,9 @@ def tree_to_nested_dict_key(
171172 >>> tree_to_nested_dict_key(root, all_attrs=True)
172173 {'a': {'age': 90, 'children': {'b': {'age': 65, 'children': {'d': {'age': 40}, 'e': {'age': 35}}}, 'c': {'age': 60}}}}
173174
175+ >>> tree_to_nested_dict_key(root, child_key=None)
176+ {'a': {'b': {'d': {}, 'e': {}}, 'c': {}}}
177+
174178 Args:
175179 tree: tree to be exported
176180 child_key: dictionary key for children
@@ -190,16 +194,25 @@ def _recursive_append(_node: T, parent_dict: Dict[str, Any]) -> None:
190194 _node: current node
191195 parent_dict: parent dictionary
192196 """
197+ if child_key is None :
198+ if attr_dict or all_attrs :
199+ raise ValueError (
200+ "If child_key is None, no node attributes can be exported"
201+ )
202+
193203 if _node :
194204 if not max_depth or _node .depth <= max_depth :
195205 data_child = common .assemble_attributes (_node , attr_dict , all_attrs )
196- if child_key in parent_dict :
197- parent_dict [child_key ][_node .node_name ] = data_child
206+ if child_key :
207+ if child_key in parent_dict :
208+ parent_dict [child_key ][_node .node_name ] = data_child
209+ else :
210+ parent_dict [child_key ] = {_node .node_name : data_child }
198211 else :
199- parent_dict [child_key ] = { _node .node_name : data_child }
212+ parent_dict [_node .node_name ] = data_child
200213
201214 for _child in _node .children :
202215 _recursive_append (_child , data_child )
203216
204217 _recursive_append (tree , data_dict )
205- return data_dict [child_key ]
218+ return data_dict [child_key ] if child_key else data_dict
0 commit comments