Tree structure

Bevan Jenkins bevan07 at gmail.com
Wed Jul 27 01:23:45 CEST 2011


On Jul 26, 8:46 pm, Peter Otten <__pete... at web.de> wrote:
> Bevan Jenkins wrote:
> > Hello,
>
> > I am trying to create a tree structure for use with a PyQt QTreeView.
> > But first I need to get my head around how to create the tree
> > structure.  I have a dictionary (for testing purposes) but I will
> > later use a table via sqlalchemy.
>> SNIP<<
> > Any thoughts about how to acomplish this will be much appreciated,
> > Bevan
>
> If you turn the values into lists you can use the same function for both
> trees:
>
> INDENT = " " * 4
>
> def print_tree(lookup, node=None):
>     def _tree(node, level):
>         print "%s%s" % (INDENT * level, node)
>         for node in lookup.get(node, ()):
>             _tree(node, level+1)
>
>     if node is None:
>         for node in lookup:
>             _tree(node, 0)
>     else:
>         _tree(node, 0)
>
> def reversed_dict(tree):
>     reversed_tree = {}
>     for key, values in rivers.iteritems():
>         for value in values:
>             reversed_tree.setdefault(value, []).append(key)
>     return reversed_tree
>
> if __name__ == "__main__":
>     rivers = {
>         "little stream": "sea",
>         "mountain stream": "lake",
>         "lake": "big river",
>         "cold spring": "big river",
>         "big river": "sea",
>         "see": ""}
>
>     rivers = dict((k, [v]) for k, v in rivers.iteritems() if v)
>     print_tree(rivers)
>     print "---"
>     print_tree(reversed_dict(rivers), "sea")- Hide quoted text -
>
> - Show quoted text -

Peter,
Thank you that does what I need!  Now I just need to incorporate into
PyQt but that shouldn't be too hard...

Macro,
I need to look into lxml in the coming months, so I might revisit this
then.



More information about the Python-list mailing list