2
votes

I want to create a N-ary tree in which each node will contain a key(name) and a value.

1 root then N children with two fields = name and associate value and again each children have N-children with 2 fields.

looking for simpler approach without using class using only dictionary and lists (if possible??).

class Node():
    #Do something
    # ....
2
You mean like {'name': ..., 'value': ..., 'children': [...]}? - jonrsharpe
but its not like tree.. If I'm at certain node I should be able to access only its childrens - pankaj udaas
I don't understand what your issue is. You can access node['children']. - jonrsharpe
@pankajudaas: This is for one node. The list named 'children' will contain references to the other nodes that look the same way. It is quite normal for the tree that you can go only to the children. You have to remember the upper node somewhere else if you want to go back. - pepr

2 Answers

7
votes
class Node(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value
        self.children = []
    def add_child(self, obj):
        self.children.append(obj)

You say youre looking for a "simpler approach without using class" but my claim here is that 9 times out of 10 using a class for this will be the simpler approach.

0
votes

If you insist on not using classes:

def create_node(name, value):
    return {
        'name': name,
        'value': value,
        'children': []
    }

def add_child(node, obj):
    node['children'].append(obj)

########################################
node = create_node('foo', 0)
add_child(node, create_node('bar', 1))

print(node) 
# Result: {'name': 'foo', 'value': 0, 'children': [{'name': 'bar', 'value': 1, 'children': []}]}