Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a good Python Tree data structure [closed]

Tags:

python

I am looking for a good Tree data structure class. I have come across this package, but since I am relatively new to Python (not programming), I dont know if there are any better ones out there.

I'd like to hear from the Pythonistas on here - do you have a favorite tree script that you regularly use and would recommend?

[Edit]

To clarify, by 'Tree', I mean a simple unordered tree (Hmm, thats a bit of a recursive definition - but hopefully, that clarifies things somewhat). Regarding what I need the tree for (i.e. use case). I am reading tree data from a flat file and I need to build a tree from the data and traverse all nodes in the tree.

like image 929
morpheous Avatar asked Jun 09 '10 21:06

morpheous


People also ask

Is there a tree data structure in Python?

Trees are non-linear data structures that represent nodes connected by edges. Each tree consists of a root node as the Parent node, and the left node and right node as Child nodes.

How do you program a tree in Python?

To create a tree in Python, we first have to start by creating a Node class that will represent a single node. This Node class will contain 3 variables; the first is the left pointing to the left child, the second variable data containing the value for that node, and the right variable pointing to the right child.


2 Answers

You can build a nice tree of dicts of dicts like this:

import collections  def Tree():     return collections.defaultdict(Tree) 

It might not be exactly what you want but it's quite useful! Values are saved only in the leaf nodes. Here is an example of how it works:

>>> t = Tree() >>> t defaultdict(<function tree at 0x2142f50>, {}) >>> t[1] = "value" >>> t[2][2] = "another value" >>> t defaultdict(<function tree at 0x2142f50>, {1: 'value', 2: defaultdict(<function tree at 0x2142f50>, {2: 'another value'})})  

For more information take a look at the gist.

like image 122
Stefan Avatar answered Oct 15 '22 04:10

Stefan


I found a module written by Brett Alistair Kromkamp which was not completed. I finished it and make it public on github and renamed it as treelib (original pyTree):

https://github.com/caesar0301/treelib

May it help you....

like image 30
caesar0301 Avatar answered Oct 15 '22 03:10

caesar0301