Filter Dictionary Keys by Prefix in Python

Use a dict comprehension to build a new dictionary containing only keys that start with a given prefix.

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

Python code

21 lines
Python 3.9+
def filter_dict_keys(data, prefix="temp_"):
    """
    Filter a dictionary by keeping only keys that start with a given prefix.
    Uses a dict comprehension to build a new dictionary.
    """
    if not isinstance(data, dict):
        raise ValueError("data must be a dictionary")
    return {key: value for key, value in data.items() if key.startswith(prefix)}

if __name__ == "__main__":
    sample_data = {
        "temp_celsius": 22.5,
        "temp_fahrenheit": 72.5,
        "humidity": 60,
        "pressure": 1013,
        "temp_kelvin": 295.65,
    }
    filtered = filter_dict_keys(sample_data)
    print(filtered)
    # Show how to filter with a different prefix
    print(filter_dict_keys(sample_data, prefix="hum"))

Output

stdout
{'temp_celsius': 22.5, 'temp_fahrenheit': 72.5, 'temp_kelvin': 295.65}
{'humidity': 60}

How it works

The filter_dict_keys function takes a dictionary and an optional prefix parameter, defaulting to "temp_". Inside, it uses a dict comprehension with a conditional expression (if key.startswith(prefix)) to include only the key-value pairs whose keys match the prefix. This approach creates a brand new dictionary, leaving the original data unchanged, which is a safe pattern for filtering data in production code. The type check isinstance(data, dict) guards against passing non-dictionary values.

Common mistakes

  • Forgetting that the original dictionary is not modified — you must use the returned value
  • Using `dict.items()` without including both `key` and `value` in the comprehension
  • Assuming `startswith` is case-sensitive when case-insensitive matching is needed

Variations

  1. Use a lambda with `filter` and `dict()` for a functional approach
  2. Filter by a suffix with `endswith()`, or by a substring with `in`

Real-world use cases

  • Extracting only environment variables that share a common prefix, like `AWS_` or `DB_`, from a configuration dictionary.
  • Processing sensor telemetry by filtering readings for specific metrics (e.g., only `temp_` keys) before aggregation.
  • Filtering API response payloads to keep only whitelisted fields with a shared naming convention before persisting to storage.

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.