Category and subcategory classes. Need code example

Question:

I have dict type dataset like [{id, category, parent_id},]. I need create class for parse this dataset and create simple interface to get parents and childrens. I dnt want to invent a wheel, can someone share the code that will help me to implement this task?

I tried to create data classes and then make classes to implement methods for working with them, but I’m tired of thinking about a competent implementation. Time goes by and no results.

Asked By: fallenreds

||

Answers:

from dataclasses import dataclass

@dataclass
class Node:
    id: int
    category: str
    parent_id: int

class Tree:
    def __init__(self, dataset):
        self.nodes = {d["id"]: Node(d["id"], d["category"], d["parent_id"]) for d in dataset}
        
    def get_parent(self, node_id: int) -> Node:
        return self.nodes.get(self.nodes[node_id].parent_id)
        
    def get_children(self, node_id: int) -> List[Node]:
        children = []
        for id, node in self.nodes.items():
            if node.parent_id == node_id:
                children.append(node)
        return children

This way, you can create a Tree object by passing in your dataset, and then use the get_parent and get_children methods to retrieve parent and children nodes respectively.

You can use the following way to create an object of Tree class and use the methods:

dataset = [{'id': 1, 'category': 'cat1', 'parent_id': None}, 
           {'id': 2, 'category': 'cat2', 'parent_id': 1}, 
           {'id': 3, 'category': 'cat3', 'parent_id': 2},
           {'id': 4, 'category': 'cat4', 'parent_id': 1},
           {'id': 5, 'category': 'cat5', 'parent_id': 4}]

tree = Tree(dataset)
parent = tree.get_parent(3)
childrens = tree.get_children(1)
Answered By: Nova