Skip to content

Instantly share code, notes, and snippets.

@embayer
Created January 17, 2017 15:04
Show Gist options
  • Save embayer/2722d4827046e0e8bdf8afd805a5c917 to your computer and use it in GitHub Desktop.
Save embayer/2722d4827046e0e8bdf8afd805a5c917 to your computer and use it in GitHub Desktop.
generate a category tree from a list of category strings
def gen_tree(self, category_strs):
''' takes an array of category strings eg:
["Heim & Garten > Rasen & Garten > Bewässerungssysteme",
"Heim & Garten > Rasen & Garten > Gartenbau"]
and returns an category tree dict eg:
{
"root": {
"children:": {
"Heim & Garten": {
"slug": {
"heim-garten"
}
"children": {
"Rasen & Garten": {
"slug": {
"rasen-garten"
}
"children": {
"Bewässerungssysteme": {},
"Gartenbau": {}
}
}
}
}
}
}
}
'''
def merge(subcat, current_obj):
# if new
if subcat not in current_obj['children']:
# go a level deeper
children = {'slug': slugify(subcat), 'children': {}}
# append
current_obj['children'][subcat] = children
else:
# go a level deeper
children = current_obj['children'][subcat]
return children
# init
tree = {'root': {'children': {}}}
for category_str in category_strs:
# move 'pointer' to the beginning
current_obj = tree['root']
splitted = category_str.split(' > ')
for category in splitted:
current_obj = merge(category, current_obj)
return tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment