Python print nested list as tree
I want to define two functions, one that prints a tree out from a nested list and the other that prints a tree from a flat list. For exaple, if we have the lists
This is the Binary Tree implementation
I basically want to convert the list into a tree because there is a create string function in the Binary Tree class Given a nested list we want to convert it to a dictionary whose elements can be considered as part of a tree data structure. In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure. Using SlicingWe reverse the items in the list aby slicing and then check if the item is present in the list. If it is not present we ignore it else we add it to the tree. Exampledef CreateTree(lst): new_tree = {} for list_item in lst: currTree = new_tree for key in list_item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return new_tree # Given list listA = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']] print(CreateTree(listA)) Running the above code gives us the following result − Output{'X': {'Y': {}, 'Z': {'P': {}}}} Using reduce and getitemWe use the functools and operator module to get the functions reduce and getitem. Using these functions we define two functions to get the items from the list and set the items into a tree structure. Here also we use the slicing approach to reverse the elements of the list and then apply the two created functions to create the dictionaries whose elements are in tree structure. Examplefrom functools import reduce from operator import getitem def getTree(tree, mappings): return reduce(getitem, mappings, tree) def setTree(tree, mappings): getTree(tree, mappings[:-1])[mappings[-1]] = dict() # Given list lst = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']] tree = {} for i in lst: setTree(tree, i[::-1]) print(tree) Running the above code gives us the following result − Output{'X': {'Y': {}, 'Z': {'P': {}}}}
Updated on 28-Dec-2020 11:19:45
If you can use dict only: l = [ [1], [2, 3], [2, 4], [2, 5], [2, 5, 6], [2, 5, 7], [2, 5, 8], [2, 5, 8, 9], [10], [11, 12] ] root = {} for path in l: parent = root for n in path: parent = parent.setdefault(n, {}) import pprint pprint.pprint(root, width = 1) output: { 1: {}, 2: { 3: {}, 4: {}, 5: { 6: {}, 7: {}, 8: { 9: {} } } }, 10: {}, 11: { 12: {} } } Suggestion : 2 Python program to convert a list into a list of lists using a step value,Given a nested list we want to convert it to a dictionary whose elements can be considered as part of a tree data structure. In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure.,Convert a string representation of list into list in Python,Convert list into list of lists in Python Exampledef CreateTree(lst): new_tree = {} for list_item in lst: currTree = new_tree for key in list_item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return new_tree # Given list listA = [ ['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X'] ] print(CreateTree(listA)) Output{ 'X': { 'Y': {}, 'Z': { 'P': {} } } } Suggestion : 3 2016-01-15 @ 22:16:33 [{ "node": 1, "ancestors": [], "label": "Australia" }, { "node": 2, "ancestors": [1], "label": "South Australia" }, { "node": 3, "ancestors": [1], "label": "Victoria" }, { "node": 4, "ancestors": [1, 2], "label": "South-East" }, { "node": 5, "ancestors": [1, 3], "label": "Western Districts" }, { "node": 6, "ancestors": [], "label": "New Zealand" }, { "node": 7, "ancestors": [1, 2], "label": "Barossa Valley" }, { "node": 8, "ancestors": [1, 2], "label": "Riverland" } ] [ ('Australia', [ ('South Australia', [ ('Barossa Valley', []), ('Riverland', []), ('South-East', []) ]), ('Victoria', [ ('Western Districts', []) ]) ]), ('New Zealand', []) ] { 1: { 2: { 4: {}, 7: {}, 8: {}, }, 3: { 5: {}, } }, 6: {}, } class Tree(dict): def __missing__(self, key): value = self[key] = type(self)() return value def insert(self, key, ancestors): if ancestors: self[ancestors[0]].insert(key, ancestors[1: ]) else : self[key] >>> tree = Tree() >>> for node in data: ...tree.insert(node['node'], node['ancestors']) >>> print tree { 1: { 2: { 8: {}, 4: {}, 7: {} }, 3: { 5: {} } }, 6: {} } Suggestion : 4 How the list is structured. "simple" (the default) will interpret any list to be a child. "explicit" assumes that children are in a nested list called childrenName,A list in which children are stored as nested list alongside other attributes. Any list is interpreted as a child Node,The name of the element in the list that should be used as the name, can be NULL if mode = explicit and the children lists are named, or if an automatic name (running number) should be assigned,A list in which children are in a separate nested list called childrenName. 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 # # S3 method for class 'list' as.Node( x, mode = c("simple", "explicit"), nameName = "name", childrenName = "children", nodeName = NULL, check = c("check", "no-warn", "no-check"), ... ) FromListExplicit( explicitList, nameName = "name", childrenName = "children", nodeName = NULL, check = c("check", "no-warn", "no-check") ) FromListSimple( simpleList, nameName = "name", nodeName = NULL, check = c("check", "no-warn", "no-check") ) 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 41 42 kingJosephs < -list(name = "Joseph I", spouse = "Mary", born = "1818-02-23", died = "1839-08-29", children = list( list(name = "Joseph II", spouse = "Kathryn", born = "1839-03-28", died = "1865-12-19"), list(name = "Helen", born = "1840-17-08", died = "1845-01-01") ) ) FromListExplicit(kingJosephs) kingJosephs < -list(head = "Joseph I", spouse = "Mary", born = "1818-02-23", died = "1839-08-29", list(head = "Joseph II", spouse = "Kathryn", born = "1839-03-28", died = "1865-12-19"), list(head = "Helen", born = "1840-17-08", died = "1845-01-01") ) FromListSimple(kingJosephs, nameName = "head") kingJosephs < -list(spouse = "Mary", born = "1818-02-23", died = "1839-08-29", `Joseph II` = list(spouse = "Kathryn", born = "1839-03-28", died = "1865-12-19"), Helen = list(born = "1840-17-08", died = "1845-01-01") ) FromListSimple(kingJosephs, nodeName = "Joseph I") levelName 1 Joseph I 2 00A6>--Joseph II 3 00B0>--Helen levelName 1 Joseph I 2 00A6>--Joseph II 3 00B0>--Helen levelName 1 Joseph I 2 00A6>--Joseph II 3 00B0>--Helen Suggestion : 5 ActiveCode 2 exercises the tree functions we have just written. You should try it out for yourself. One of the exercises asks you to draw the tree structure resulting from this set of calls.,Let’s formalize this definition of the tree data structure by providing some functions that make it easy for us to use lists as trees. Note that we are not going to define a binary tree class. The functions we will write will just help us manipulate a standard list as though we are working with a tree.,The BinaryTree function simply constructs a list with a root node and two empty sublists for the children. To add a left subtree to the root of a tree, we need to insert a new list into the second position of the root list. We must be careful. If the list already has something in the second position, we need to keep track of it and push it down the tree as the left child of the list we are adding. Listing 1 shows the Python code for inserting a left child.,Write a function buildTree that returns a tree using the list of lists functions that looks like this: myTree = ['a', #root['b', #left subtree['d', [], []], ['e', [], [] ]], ['c', #right subtree['f', [], []], [] ] ] def BinaryTree(r): return [r, [], [] ] def insertLeft(root, newBranch): t = root.pop(1) if len(t) > 1: root.insert(1, [newBranch, t, []]) else : root.insert(1, [newBranch, [], [] ]) return root def insertRight(root, newBranch): t = root.pop(2) if len(t) > 1: root.insert(2, [newBranch, [], t]) else : root.insert(2, [newBranch, [], [] ]) return root def getRootVal(root): return root[0] def setRootVal(root, newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] x = BinaryTree('a') insertLeft(x, 'b') insertRight(x, 'c') insertRight(getRightChild(x), 'd') insertLeft(getRightChild(getRightChild(x)), 'e') |