sort dict tree by id :)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from random import randint
varss = [{'id': x, 'parent': randint(0, 10)} for x in range(10)]
vars_ = [{'id': x, 'parent': None} for x in range(10, 15)]
vars_ += varss
def pretty(d, indent=0):
if isinstance(d, list):
for x in d:
pretty(x, indent + 1)
else:
for key, value in d.iteritems():
print ('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent + 1)
else:
print('\t' * (indent + 1) + str(value))
def sort_tree(items):
res = []
first_column = [x for x in items if x.get('id') == 0 or
x.get('parent') is None]
first_column = sorted(
first_column, key=lambda y: y.get('id')) # reverse=True
items_dict = {}
for x in items:
x['children'] = []
items_dict[x['id']] = x
items = sorted(items, key=lambda y: y.get('id'))
for x in items:
id = x.get('parent')
if not id:
continue
items_dict[id]["children"].append(x)
print(items)
return first_column
# print(vars_)
print(pretty(sort_tree(vars_)))