How to Sort Data in Python with a Class Helper
This beginner-friendly class wraps the built-in sorted() function to sort numbers, strings ignoring case, and dictionaries by a specified key.
Python code
27 linesclass DataSorter:
def __init__(self, data):
self.data = data
def sort_numbers(self, reverse=False):
return sorted(self.data, reverse=reverse)
def sort_strings_ignore_case(self, reverse=False):
return sorted(self.data, key=str.lower, reverse=reverse)
def sort_dicts_by_key(self, key, reverse=False):
return sorted(self.data, key=lambda item: item[key], reverse=reverse)
if __name__ == "__main__":
numbers = [4, 2, 8, 1, 5]
number_sorter = DataSorter(numbers)
print("Numbers ascending:", number_sorter.sort_numbers())
print("Numbers descending:", number_sorter.sort_numbers(reverse=True))
words = ["Banana", "apple", "Cherry", "date"]
word_sorter = DataSorter(words)
print("Strings (ignore case):", word_sorter.sort_strings_ignore_case())
people = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Charlie", "age": 35}]
person_sorter = DataSorter(people)
print("By age:", person_sorter.sort_dicts_by_key("age"))
Output
Numbers ascending: [1, 2, 4, 5, 8]
Numbers descending: [8, 5, 4, 2, 1]
Strings (ignore case): ['apple', 'Banana', 'Cherry', 'date']
By age: [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
How it works
The DataSorter class encapsulates sorting logic, making it reusable and easy to extend. It uses sorted() which returns a new list without modifying the original self.data. For case-insensitive string sorting, key=str.lower normalizes strings to lowercase for comparison. For dictionaries, a lambda function extracts the selected key to serve as the sorting criterion.
Common mistakes
- Forgetting that `sorted()` returns a new list; using `sort()` on the original data would modify it.
- Using `key=str.lower` without ensuring all elements are strings.
- Not handling missing dictionary keys in `sort_dicts_by_key`; a KeyError will occur.
- Assuming reverse=True affects only the order; it reverses the resulting sorted list.
Variations
- Use `data.sort()` if you want to sort the list in-place instead of creating a new list.
- Add a `stable` parameter to control the `sorted` function's stability or use `key` with multiple criteria via tuples.
Real-world use cases
- A utility class in a data analysis script that sorts imported CSV rows by various columns.
- A small helper in a web app to sort API responses by query parameters like name or date.
- A teaching example for beginners to understand OOP by wrapping built-in functions.
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.