Created
January 17, 2017 15:04
-
-
Save embayer/2722d4827046e0e8bdf8afd805a5c917 to your computer and use it in GitHub Desktop.
generate a category tree from a list of category strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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