Python
dictionary
filtering
programming
guide

How to filter a dictionary according to an arbitrary condition function?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Filtering a dictionary by arbitrary conditions is a core Python task in data processing, API responses, and configuration handling. The goal is to keep only key-value pairs that satisfy custom logic, such as value ranges, key patterns, or type checks. Although this is conceptually simple, production code benefits from choosing the right style for readability, performance, and debuggability.

The most common technique is dictionary comprehension, but generator-based pipelines, helper functions, and explicit loops are all useful depending on complexity. This article shows reliable patterns and how to design condition functions that remain maintainable as requirements evolve.

Core Sections

1. Dictionary comprehension for concise filtering

For straightforward predicates, comprehension is the cleanest option.

python
1scores = {"alice": 91, "bob": 67, "carol": 88, "dave": 72}
2passing = {k: v for k, v in scores.items() if v >= 70}
3print(passing)
4# {'alice': 91, 'carol': 88, 'dave': 72}

This reads left-to-right: iterate items, apply condition, build new dictionary. It is fast and idiomatic for most use cases.

2. Reusable condition functions for complex logic

When the logic becomes non-trivial, move it into a named function. This improves testing and avoids unreadable inline expressions.

python
1def is_valid_user(key: str, value: dict) -> bool:
2    if not isinstance(value, dict):
3        return False
4    if value.get("active") is not True:
5        return False
6    if value.get("quota", 0) < 100:
7        return False
8    return key.startswith("team-")
9
10users = {
11    "team-alpha": {"active": True, "quota": 120},
12    "team-beta": {"active": False, "quota": 300},
13    "guest-1": {"active": True, "quota": 200},
14}
15
16filtered = {k: v for k, v in users.items() if is_valid_user(k, v)}
17print(filtered)
18# {'team-alpha': {'active': True, 'quota': 120}}

This style scales better when your predicate has business rules.

3. Parameterized predicates and composable filters

You can compose filters for flexible APIs.

python
1from typing import Callable, Dict, Any
2
3Predicate = Callable[[str, Any], bool]
4
5def filter_dict(data: Dict[str, Any], predicate: Predicate) -> Dict[str, Any]:
6    return {k: v for k, v in data.items() if predicate(k, v)}
7
8def value_between(low: int, high: int) -> Predicate:
9    return lambda k, v: isinstance(v, (int, float)) and low <= v <= high
10
11def key_contains(text: str) -> Predicate:
12    return lambda k, v: text in k
13
14inventory = {"cpu-1": 42, "gpu-2": 95, "cpu-3": 73, "disk-9": 88}
15
16mid_usage = filter_dict(inventory, value_between(50, 90))
17cpu_only = filter_dict(inventory, key_contains("cpu"))

For very large datasets, prefer generator pipelines upstream and filter before constructing heavy nested values.

Common Pitfalls

  • Mutating the original dictionary while iterating over it, which raises runtime errors or causes skipped items.
  • Packing too much logic into one comprehension, making conditions hard to review and test.
  • Ignoring type validation in predicates, which leads to brittle behavior on mixed or malformed data.
  • Recomputing expensive predicate work per item instead of precomputing lookup sets or compiled regexes.
  • Assuming dictionary order does not matter; modern Python preserves insertion order, which can affect downstream behavior.

Summary

To filter dictionaries effectively, default to dictionary comprehension for simple rules and move complex conditions into named, testable predicate functions. For reusable systems, expose a filter_dict helper that accepts predicates and supports composition. This keeps filtering logic clear, extensible, and safe under changing requirements.

As filtering rules evolve, version your predicates the same way you version API contracts. A predicate that once accepted nullable values might later require strict types or additional business fields. Encapsulating these rules in named functions makes behavior changes explicit and testable. Add unit tests for boundary conditions (missing keys, wrong types, empty strings, extreme numeric values) so regressions are detected early.

Performance tuning should focus on predicate cost, not just dictionary size. If a predicate uses regex matching, parse-heavy conversions, or database lookups, memoization and precomputation can provide larger gains than micro-optimizing comprehension syntax. In data pipelines, consider filtering as early as possible to avoid carrying invalid entries into expensive downstream transforms. Clear predicate design plus early filtering typically yields both cleaner code and faster execution.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms