Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement