How to Filter a List of Dictionaries by Category in Python

Filter a list of dictionaries to include only records whose category is in an allowed set.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

20 lines
Python 3.9+
def filter_data(records, categories):
    """Return only records whose category is in the allowed set."""
    allowed = set(categories)
    filtered = []
    for record in records:
        if record["category"] in allowed:
            filtered.append(record)
    return filtered


if __name__ == "__main__":
    data = [
        {"name": "apple", "category": "fruit"},
        {"name": "carrot", "category": "vegetable"},
        {"name": "banana", "category": "fruit"},
        {"name": "broccoli", "category": "vegetable"},
        {"name": "chicken", "category": "meat"},
    ]
    result = filter_data(data, ["fruit", "vegetable"])
    print([item["name"] for item in result])

Output

stdout
['apple', 'carrot', 'banana', 'broccoli']

How it works

The function converts the categories list into a set for O(1) membership checks, making the filtering efficient even for large lists. It iterates over each record and uses the in operator to test if the record's category key is in the allowed set. Only records whose category is allowed are appended to the filtered list. This pattern is a common way to filter data by a set of allowed values using dictionary key access.

Common mistakes

  • Forgetting to convert the categories list to a set, which reduces performance.
  • Assuming the records always have the 'category' key, which raises a KeyError if missing.
  • Returning the list in a different order than the input, which could break expectations.

Variations

  1. Use a list comprehension: `[r for r in records if r['category'] in allowed]` for more concise code.
  2. Use `filter()` with a lambda for functional programming style.

Real-world use cases

  • Filtering user-generated content by allowed content types before processing.
  • Selecting rows from an imported dataset (like CSV) based on category columns.
  • Filtering log entries by severity levels before writing to a monitoring system.

Sponsored

Run this sample

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

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.