How to Filter a Dictionary by Predicate on Values in Python
This code defines a reusable function that builds a new dictionary containing only the items whose values satisfy a given predicate function.
Python code
15 linesdef filter_dict_by_predicate(d, predicate):
"""Return a new dict with only items whose value passes the predicate."""
return {k: v for k, v in d.items() if predicate(v)}
if __name__ == "__main__":
scores = {"Alice": 85, "Bob": 42, "Charlie": 91, "Diana": 60}
# Keep only values greater than or equal to 70
passed = filter_dict_by_predicate(scores, lambda x: x >= 70)
print(passed)
# Keep only even-length strings
words = {"a": "hi", "b": "hello", "c": "world"}
even_len = filter_dict_by_predicate(words, lambda s: len(s) % 2 == 0)
print(even_len)
Output
{'Alice': 85, 'Charlie': 91}
{'a': 'hi'}
How it works
The function filter_dict_by_predicate uses a dictionary comprehension to iterate over key‑value pairs from the original dict. For each pair, it checks whether predicate(v) returns True; if so, the key and value are included in the new dictionary. Because dictionaries are unordered in older Python versions, but insertion order is preserved in Python 3.7+, the output key order matches the original insertion order. Passing a lambda keeps the function generic — you can filter on any property of the value, not just numbers. The function returns a new dict and leaves the original untouched, making it a pure, side‑effect‑free utility.
Common mistakes
- Using `filter()` directly returns an iterable of keys, not a dict, unless you wrap it in another comprehension.
- Forgetting that any falsy value (like `0`, `""`, or `None`) fails a truthiness predicate, which may surprise you.
- Checking the key instead of the value when the predicate is meant for values.
- Mutating the original dictionary inside the loop instead of building a new one.
Variations
- Use `d.items()` and a simple loop with an if statement to build the result step by step.
- For filtering by key, create a variation that applies the predicate to the key instead of the value.
Real-world use cases
- Removing spurious entries from a data source, such as discarding readings below a confidence threshold.
- Preparing a configuration dictionary for a service, keeping only settings that pass validation criteria.
- Building a filtered feature map from a model's output, retaining only high‑confidence predictions.
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.