The nested dictionary tree is of the form,
categories = [{
'name': 'Cat1',
'children': [{
'name': 'SubCat1',
'children': [{
'name': 'SubSubCat1',
'children': []
}]
}]
}, {
'name': 'Cat2',
'children': []
}]
The recursive function should return the path from root to a specific leaf.
Lets say, function(categories, 'SubCat1')
should return a list containing ['Cat1', 'SubCat1']
. Likewise for function(categories, 'Cat2')
should return the ['Cat2']
.
Progress made so far
def recurse_category(categories, to_find):
def _recurse_category(categories, to_find, path=[]):
for category in categories:
path.append(category['name'])
if len(category['children']) == 0 and category['name'] != to_find:
return path, False
if category['name'] == to_find:
return path, True
else:
recurse_category(
category['children'], to_find, path
)
return _recurse_category(categories, to_find, path=[])