Hierarchical Category Management System

By: fyvo August 2, 2025 Python

Description

This Python code demonstrates a simple hierarchical category system using nested dictionaries. Categories can be added, retrieved, and their structure inspected.

Code Snippet

class Category:
    def __init__(self, name, parent=None):
        self.name = name
        self.parent = parent
        self.children = {}

    def add_child(self, child_category):
        self.children[child_category.name] = child_category

    def get_child(self, child_name):
        return self.children.get(child_name)

    def print_tree(self, indent=0):
        print('  ' * indent + self.name)
        for child in self.children.values():
            child.print_tree(indent + 1)

# Example usage
root = Category('Electronics')
computers = Category('Computers', root)
laptops = Category('Laptops', computers)
desktops = Category('Desktops', computers)
phones = Category('Phones', root)
root.add_child(computers)
root.add_child(phones)
computers.add_child(laptops)
computers.add_child(desktops)

root.print_tree()

Discussion (0)