Group Data Helper Class in Python

A simple Python class that stores items under named groups, retrieves groups, items, and counts, and formats them as a readable summary.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 14 views 0 copies

Python code

49 lines
Python 3.9+
class GroupData:
    """A simple helper class to store and group data for beginners."""

    def __init__(self):
        self.items = []

    def add(self, item, group):
        """Add an item under a given group name."""
        self.items.append({"item": item, "group": group})

    def get_groups(self):
        """Return a list of all unique group names."""
        return list({entry["group"] for entry in self.items})

    def items_in_group(self, group):
        """Return all items that belong to the given group."""
        return [entry["item"] for entry in self.items if entry["group"] == group]

    def group_counts(self):
        """Return a dictionary mapping each group to its item count."""
        counts = {}
        for entry in self.items:
            group = entry["group"]
            counts[group] = counts.get(group, 0) + 1
        return counts

    def __str__(self):
        """Human-readable summary of the grouped data."""
        lines = ["Grouped data:"]
        for group in self.get_groups():
            items = ", ".join(self.items_in_group(group))
            lines.append(f"  {group}: {items}")
        return "\n".join(lines)


if __name__ == "__main__":
    # Demonstrate usage with fruits and colors
    db = GroupData()
    db.add("apple", "fruit")
    db.add("banana", "fruit")
    db.add("carrot", "vegetable")
    db.add("red", "color")
    db.add("blue", "color")
    db.add("broccoli", "vegetable")

    print(db)
    print("\nGroups:", db.get_groups())
    print("Fruit items:", db.items_in_group("fruit"))
    print("Counts:", db.group_counts())

Output

stdout
Grouped data:
  fruit: apple, banana
  vegetable: carrot, broccoli
  color: red, blue

Groups: ['fruit', 'vegetable', 'color']
Fruit items: ['apple', 'banana']
Counts: {'fruit': 2, 'vegetable': 2, 'color': 2}

How it works

This class encapsulates the logic for grouping data, making it reusable and easy to maintain. The add method stores each item and its group as a dictionary inside a list. Using a set in get_groups ensures unique group names. The group_counts method leverages the get method of dictionaries to increment counts safely. Finally, __str__ provides a human-readable representation by iterating over groups and joining items.

Common mistakes

  • Forgetting to initialize `self.items` in `__init__`, causing AttributeError.
  • Trying to modify the list returned by `get_groups` as if it were the internal list — it's a new list.
  • Assuming the order of groups from `get_groups` is insertion order; sets do not preserve order.

Variations

  1. Use `defaultdict(list)` to store items directly under group keys.
  2. Implement `__repr__` to return a machine-readable representation instead of a human-friendly one.

Real-world use cases

  • Grouping log entries by severity level before writing a summary report.
  • Categorizing products by department for inventory-based analytics.
  • Organizing user feedback by topic to triage support tickets.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.