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.
Python code
21 linesdef 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
{'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
- Use a lambda with `filter` and `dict()` for a functional approach
- 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
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.