Filtering data with a Python class helper
A beginner-friendly DataFilter class that filters lists of dictionaries by exact match, greater-than, and substring conditions.
Python code
32 linesclass DataFilter:
"""A beginner-friendly helper to filter lists of dictionaries."""
def __init__(self, data):
self.data = data
def filter_by(self, key, value):
"""Return items where data[key] == value."""
return [item for item in self.data if item.get(key) == value]
def filter_gt(self, key, threshold):
"""Return items where data[key] > threshold."""
return [item for item in self.data if item.get(key, 0) > threshold]
def filter_contains(self, key, substring):
"""Return items where substring is in str(data[key])."""
return [item for item in self.data
if substring.lower() in str(item.get(key, "")).lower()]
if __name__ == "__main__":
people = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Boston"},
{"name": "Charlie", "age": 35, "city": "New York"},
{"name": "Diana", "age": 28, "city": "Chicago"}
]
helper = DataFilter(people)
print(helper.filter_by("city", "New York"))
print(helper.filter_gt("age", 27))
print(helper.filter_contains("name", "li"))
Output
[{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}]
[{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}]
[{'name': 'Alice', 'age': 30, 'city': 'New York'}, {'name': 'Charlie', 'age': 35, 'city': 'New York'}]
How it works
The DataFilter class encapsulates the data and provides three filter methods, each returning a new list. filter_by uses item.get(key) == value for exact matching, filter_gt compares values with a default of 0 for missing keys, and filter_contains performs a case-insensitive substring check. Using item.get() prevents KeyError when a key is missing, making the helper robust for real-world data.
Common mistakes
- Using item[key] instead of item.get(key), leading to KeyError on missing keys
- Forgetting to convert values to strings for substring matching, causing TypeError on non-string values
- Mutating the original data instead of returning a new filtered list
- Not handling case sensitivity in substring search when needed
Variations
- Use a lambda with the built-in filter() function for one-off filters
- Add a generic filter method that accepts a callable predicate
Real-world use cases
- Filtering user records from an API response by role or status in a dashboard.
- Quickly extracting rows from a database result set that exceed a threshold for reporting.
- Searching a list of log entries by keyword to debug incidents in production.
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.