Fjallbacka
Fjallbacka

Reputation: 474

Dictionary of list as tree class

I am trying to define a tree class that can be easily managed (add nodes, get children and walk through it in dfs or bfs style) but I know just a little about python and I'm stuck with an error when running my code:

AttributeError: 'Tree' object has no attribute 'get'

This is my code, by now I've just implemented the addition of nodes:

class Tree(dict):
    def __init__(self):
        self = {}

    def add(self, node, child):
        if self.get(int(node)):
            childs = self.get(int(node))
            childs.append(int(child))
            self.update({int(node):childs})
        else:
            self.update({int(int(node)):[int(child)]})

def main():
    tot = int(input("Cantidad de relaciones: "))
    t = Tree()
    for i in range (0, tot):
        for i in range (0,1):
            a = []
            a.extend(input().split())
        t.add(a[0], a[1])
    print(t)

main()

Upvotes: 1

Views: 1683

Answers (1)

Artem Selivanov
Artem Selivanov

Reputation: 1957

Inherit it from dict!

get and update is dictionary datatype's methods.

Your code: class Tree(object): replace it with: class Tree(dict): and error will be resolved.

Also your idea with your code is strage. Python already implements tree-like data structures with dict and list datatypes.

a = {
    'a': [1, 2, 3],
    'b': {
        'c': [33, 44, 55]
        'd': 123,
    }
}

Python data structures

Upvotes: 1

Related Questions