Making a tree out of a 2 column list

mensanator at aol.com mensanator at aol.com
Sat Apr 14 12:32:07 EDT 2007


On Apr 14, 9:37�am, "Sebastian Bassi" <sba... at clubdelarazon.org>
wrote:
> I have a two column list like:
>
> 2,131
> 6,335
> 7,6
> 8,9
> 10,131
> 131,99
> 5,10
>
> And I want to store it in a tree-like structure.
> So if I request 131, it should return all the child of 131, like 2, 10
> and 5 (since 5 is child of 10).
> If I request 335, it should return: 6 and 7.
> If I request 9, it should return 8.
> I guess I could use tuples or dictionaries to do it, but I can't figure out how.

There are probably better ways.

def tree_path(key,tree,indent):
    print '\t'*indent,key
    if tree.has_key(key):
        for m in tree[key]:
            tree_path(m,tree,indent+1)
    return

print 'original data'
print

source = [(2,131),(6,335),(7,6),(8,9),(10,131),(131,99),(5,10)]

tree = {}
for s in source:
    if tree.has_key(s[1]):
        tree[s[1]].append(s[0])
    else:
        tree[s[1]] = [s[0]]

for t in tree:
    print '%3d ' % (t),tree[t]

print
print
tree_path(99,tree,0)

print
print 'extended data'
print

source_extend = [(666,2),(777,2),(888,2)]

for s in source_extend:
    if tree.has_key(s[1]):
        tree[s[1]].append(s[0])
    else:
        tree[s[1]] = [s[0]]

for t in tree:
    print '%3d ' % (t),tree[t]

print
print
tree_path(99,tree,0)

##    original data
##
##     99  [131]
##      6  [7]
##      9  [8]
##     10  [5]
##    335  [6]
##    131  [2, 10]
##
##
##     99
##        131
##            2
##            10
##                5
##
##    extended data
##
##      2  [666, 777, 888]
##     99  [131]
##      6  [7]
##      9  [8]
##     10  [5]
##    335  [6]
##    131  [2, 10]
##
##
##     99
##        131
##            2
##                666
##                777
##                888
##            10
##                5


>
> Best,
> SB.
>
> --
> Sebastián Bassi
> Diplomado Ciencia y Tecnología.
> Club de la razón (www.clubdelarazon.org)





More information about the Python-list mailing list