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.

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

Python code

32 lines
Python 3.9+
class 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

stdout
[{'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

  1. Use a lambda with the built-in filter() function for one-off filters
  2. 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

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.