Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. def gen_tree(self, category_strs):
  2. ''' takes an array of category strings eg:
  3. ["Heim & Garten > Rasen & Garten > Bewässerungssysteme",
  4. "Heim & Garten > Rasen & Garten > Gartenbau"]
  5. and returns an category tree dict eg:
  6. {
  7. "root": {
  8. "children:": {
  9. "Heim & Garten": {
  10. "slug": {
  11. "heim-garten"
  12. }
  13. "children": {
  14. "Rasen & Garten": {
  15. "slug": {
  16. "rasen-garten"
  17. }
  18. "children": {
  19. "Bewässerungssysteme": {},
  20. "Gartenbau": {}
  21. }
  22. }
  23. }
  24. }
  25. }
  26. }
  27. }
  28.  
  29. '''
  30. def merge(subcat, current_obj):
  31. # if new
  32. if subcat not in current_obj['children']:
  33. # go a level deeper
  34. children = {'slug': slugify(subcat), 'children': {}}
  35. # append
  36. current_obj['children'][subcat] = children
  37. else:
  38. # go a level deeper
  39. children = current_obj['children'][subcat]
  40. return children
  41.  
  42. # init
  43. tree = {'root': {'children': {}}}
  44.  
  45. for category_str in category_strs:
  46. # move 'pointer' to the beginning
  47. current_obj = tree['root']
  48. splitted = category_str.split(' > ')
  49. for category in splitted:
  50. current_obj = merge(category, current_obj)
  51.  
  52. return tree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement