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.
Python code
20 linesdef 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
['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
- Use a list comprehension: `[r for r in records if r['category'] in allowed]` for more concise code.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.