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.

Show

For exaple, if we have the lists [5, [10, None, None], [11, [2, None, None],[6, None, None]]], and [None, 5, 10, 11, None, None, 2, 6], we would produce a tree that looks like

 10
    5
    15
        11
        22 

This is the Binary Tree implementation

class BinaryTree:

def __init__(self, data):
    self.data = data
    self.left = None
    self.right = None

def get_left(self):
    return self.left

def get_right(self):
    return self.right

def set_left(self, tree):
    self.left = tree

def set_right(self, tree):
    self.right = tree

def set_data(self, data):
    self.data = data

def get_data(self):
    return self.data

def create_string(self, spaces): 
    info = ' ' * spaces + str(self.data) 
    if self.left != None: 
        info += self.left.create_string(spaces+4) 
    if not self.right == None: 
        info += self.right.create_string(spaces+4) 
    return info       

def __str__(self): 
    representation = self.create_string(0) 
    return representation  

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 Slicing

We 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.

Example

def 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 getitem

We 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.

Example

from 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': {}}}}

Python print nested list as tree

Updated on 28-Dec-2020 11:19:45

  • Related Questions & Answers
  • Convert list into list of lists in Python
  • Convert a list into tuple of lists in Python
  • Python program to convert a list into a list of lists using a step value
  • How to convert a list of lists into a single list in R?
  • Python - Convert List of lists to List of Sets
  • Creating DataFrame from dict of narray-lists in Python
  • Convert two lists into a dictionary in Python
  • Convert list of tuples into list in Python
  • Create a Pandas Dataframe from a dict of equal length lists in Python
  • Convert a string representation of list into list in Python
  • Python Pandas CategoricalIndex - Map values using input correspondence like a dict
  • Convert set into a list in Python
  • Python - Convert given list into nested list
  • Convert a list into a tuple in Python.
  • Convert a nested list into a flat list in Python

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

Example

def 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')