building a tree from a csv file using python
Question: My csv file has the following format

    
    
    Col1        Col2
    a           b
    b           c
    c           d
    d           e
    x           b
    y           c
    z           c
    m           x
    h           b
    i           b
    

I will create a dictionary to hold this data like this

    
    
    { b:[a,x,h,i] , c:[b,y,z], d:[c], e:[d], x:[m] } 
    

From this dictionary I want to be able to build a hierarchy. For example: when
I walk through the dictionary for 'a' I should be able to display

    
    
     a -> b -> c -> d -> e
    

Similarly for 'y'

    
    
     y -> c -> d -> e
    

I can think of this as a tree structure and imagine this to be a depth first
traversal, but I am unsure about how to achieve this with a dictionary in
python. This would not be a decision tree or a binary tree etc.


Answer: You can use [**Python-Graph**](http://code.google.com/p/python-graph/).

    
    
    pairs = read_from_csv(...)
    
    from pygraph.classes.digraph import digraph 
    gr = digraph()
    gr.add_nodes(set([x for (x,y) in pairs]+[y for (x,y) in pairs]))
    
    for pair in pairs:
        gr.add_edge(pair)
    
    #and now you can do something with the graph...
    
    from pygraph.algorithms.searching import depth_first_search
    
    print ' -> '.join(depth_first_search(gr, root='a')[1])
    print ' -> '.join(depth_first_search(gr, root='y')[1])
    

