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.
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.
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.
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.
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With