fork download
  1. def nest_list(L):
  2. idx = {}
  3. children = []
  4. root = []
  5. # first pass: index items by id
  6. # if the item has no parents, put it in the 'root' list
  7. # otherwise add it to the 'children' list which we will
  8. # process in a second pass
  9. for item in L:
  10. idx[item['id']] = item
  11. if 'parent' in item:
  12. children.append(item)
  13. else:
  14. root.append(item)
  15.  
  16. # second pass: find the parents of our children
  17. for child in children:
  18. parent = idx[child['parent']]
  19. del child['parent']
  20. try:
  21. # retrieve the list of children for this
  22. # parent
  23. childlist = parent['children']
  24. except KeyError:
  25. # this item has received no children so far
  26. # so we need to make a 'children' key and list
  27. # for it.
  28. parent['children'] = childlist = []
  29. # append this child to the parent's list of children
  30. childlist.append(child)
  31.  
  32. #all done: return new root list
  33. return root
  34.  
  35. oldlist = [{
  36. "name":"Folder 2",
  37. "id":"zRDg",
  38. "parent":"OY00",
  39. "type":"folder"
  40. },
  41. {
  42. "name":"Folder 1",
  43. "id":"OY00",
  44. "type":"folder"
  45. },
  46. {
  47. "name":"Folder 2",
  48. "id":"ZDE1",
  49. "type":"folder"
  50. },
  51. {
  52. "name":"Folder 4",
  53. "id":"aaaa",
  54. "parent":"zRDg",
  55. "type":"folder"
  56. },
  57. {
  58. "name":"DX00025.jpg",
  59. "id":"9Xdd",
  60. "parent":"OY00",
  61. "type":"jpeg"
  62. }]
  63.  
  64. from pprint import pprint
  65. newlist = nest_list(oldlist)
  66. from operator import itemgetter
  67. sar = sorted(newlist,key=itemgetter('type'))
  68. pprint(newlist)
Success #stdin #stdout 0.02s 7844KB
stdin
Standard input is empty
stdout
[{'children': [{'children': [{'id': 'aaaa',
                              'name': 'Folder 4',
                              'type': 'folder'}],
                'id': 'zRDg',
                'name': 'Folder 2',
                'type': 'folder'},
               {'id': '9Xdd', 'name': 'DX00025.jpg', 'type': 'jpeg'}],
  'id': 'OY00',
  'name': 'Folder 1',
  'type': 'folder'},
 {'id': 'ZDE1', 'name': 'Folder 2', 'type': 'folder'}]