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.
Python code
49 linesclass 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
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
- Use `defaultdict(list)` to store items directly under group keys.
- 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
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.