How to implement a tree structure in Python using namedtuple
Question: I have a key-word, e.g. friendly. It gives birth to a child-word, e.g. warm,
while descending from a parent-word, e.g. friend.

    
    
    from collections import namedtuple
    
    keyword = 'friendly'
    childword = 'warm'
    parentword = 'friend'
    
    connect=namedtuple(keyword,'children parents')
    output = connect([childword],[parentword])  
    

As a result, I can use output.children to see what are the children of my
nodeword. However, what I really want to do is to type

    
    
    friendly.children # instead of output.children
    

to see the children of the key-word friendly. How can I do this? I am
completely new to Python; I am not even sure if this is doable.


Answer: If you want to define a tree structure, you could use a namedtuple for that:

    
    
    from collections import namedtuple
    
    TreeNode = namedtuple('TreeNode', ['word', 'children'])
    
    friend = TreeNode(word='friend', children=[])
    friendly = TreeNode(word='friendly', children=[])
    warm = TreeNode(word='warm', children=[])
    
    friend.children.append(friendly)
    friendly.children.append(warm)
    
    print(friendly.children)
    

which comes up with:

    
    
    [TreeNode(word='warm', children=[])]
    

That's a very C-like way of doing things though; you're probably better off
having a single Graph or Tree data structure that stores the edge
relationships, eg:

    
    
    children = dict()
    children['friend'] = ['friendly']
    children['friendly'] = ['warm']
    
    def parents(word):
        ps = []
        for k in children:
            if word in children[k]:
                ps.append(k)
        return ps
    
    print(children['friendly'])
    print(parents('friendly'))
    

which comes up with

    
    
    ['warm']
    ['friendly']
    

There's an article on [Implementing Graphs in
Python](https://www.python.org/doc/essays/graphs/) available that you might
find useful.

