Create nodes and trees using python and convert them to visualisations – anytree

We all would have come across a situation where we would have wanted to create a tree like structure. With this article you can create

  • Directory structure

The directory structure is the organisation of files into a hierarchy of folders. It should be stable and scalable; it should not fundamentally change, only be added to. Computers have used the folder metaphor for decades as a way to help users keep track of where something can be found.

Find Files Faster: How to Organize Files and Folders
  • Family tree

family tree, or pedigree chart, is a chart representing family relationships in a conventional tree structure.

  • Binary tree

In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.

We can do this with the help of a python library called as “anytree”. First let us look at the installation process for this python library.

Installation

The library can be installed using pip in python as

pip install anytree

We may also need “graphviz” to convert the tree to visualisation or to save the trees as images.

The code

Let us see a simple example where i am creating a family tree. The code snippet for this example is,

The print statement will print something like this.

Family tree

How this works?

  1. First we need to import Node and RenderTree from anytree module.
  2. Next to create any node we should assign the node to a variable. The “Node” takes name of the node or data as an argument and also the variable to which the parent node is assigned. This should be given as the parent keyword.
  3. We can also give children as the parameter just like the parent parameter.
  4. The RenderTree class renders the tree.

To generate image

We can use the following code to generate and save the tree as an image, instead of printing it in on the terminal.

Visualization

>>> from anytree.exporter import DotExporter
>>> # graphviz needs to be installed for the next line!
>>> DotExporter(udo).to_picture("udo.png")
http://anytree.readthedocs.io/en/latest/_images/udo.png

For more details and other additional methods, the official documentation can be verified.

Happy coding!