fork download
  1. from collections import deque
  2. from operator import itemgetter
  3.  
  4. def convert_tree(lst):
  5. tree = {}
  6. queue = deque([(lst, tree)])
  7. while queue:
  8. entries, branch = queue.popleft()
  9. for key, children in map(itemgetter('key', 'children'), entries):
  10. if children:
  11. queue.append((children, branch.setdefault(key, {})))
  12. else:
  13. branch[key] = ''
  14. return tree
  15.  
  16. lst = [{'key': 'a', 'children': [{'key': 'a1', 'children': [{'key': 'a11', 'children': []}]}]},
  17. {'key': 'b', 'children': [{'key': 'b1', 'children': [{'key': 'b11', 'children': []}]}]}, ]
  18. print(convert_tree(lst))
Success #stdin #stdout 0.03s 9800KB
stdin
Standard input is empty
stdout
{'a': {'a1': {'a11': ''}}, 'b': {'b1': {'b11': ''}}}