Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [
- (None, 'Child 2', 'data1'),
- ('Child 1', 'Child 1.1', 'data2'),
- (None, 'Child 1', '')
- ]
- [
- {
- 'children': [],
- 'data': ['data1'],
- 'name': 'Child 2'
- },
- {
- 'children': [
- {
- 'children': [],
- 'data': ['data2'],
- 'name': 'Child 1.1'
- }
- ],
- 'data': [''],
- 'name': 'Child 1'
- }
- ]
- def create_tree(pairs):
- def node(): return [ROOT, [], []]
- table = defaultdict(node)
- # Build 2-way mapping between nodes
- for parent, child, data in pairs:
- table[parent][1].append(child) # parent - > children
- table[child][0] = parent # child -> parent
- table[parent][2].append(data)
- def follow(parent, childids):
- for content in childids:
- for name in content['items']:
- empty = []
- child = {
- 'name': name,
- 'children': empty,
- 'data': content['data']
- }
- parent.append(child)
- if name in table:
- this_dict = [{
- 'items': table[name][1],
- 'data': table[name][2]
- }]
- follow(empty, this_dict)
- # Recursively fill in the tree
- tree = {ROOT: []}
- roots = [{'item': k, 'data': v[2]} for k, v in table.items() if v[0] == ROOT]
- my_root_items = [{
- 'items': map(lambda s: s['item'], roots),
- 'data': map(lambda s: s['data'], roots),
- }]
- follow(tree[ROOT], my_root_items)
- return tree[ROOT]
Add Comment
Please, Sign In to add comment