PYTHON
Filter a Dictionary by Keys or Values
Learn to selectively filter a Python dictionary, creating a new dictionary containing only specific keys or values that meet certain criteria, useful for data cleaning.
data = {
'name': 'Alice',
'age': 30,
'city': 'New York',
'occupation': 'Engineer',
'is_active': True
}
# Filter by specific keys (whitelist)
selected_keys = ['name', 'city']
filtered_by_keys = {k: v for k, v in data.items() if k in selected_keys}
print("Filtered by keys:", filtered_by_keys)
# Filter by value condition (e.g., age > 25)
filtered_by_value = {k: v for k, v in data.items() if isinstance(v, int) and v > 25}
print("Filtered by value (age > 25):", filtered_by_value)
# Filter by excluding certain keys (blacklist)
excluded_keys = ['occupation', 'is_active']
filtered_excluding_keys = {k: v for k, v in data.items() if k not in excluded_keys}
print("Filtered excluding keys:", filtered_excluding_keys)
How it works: This snippet shows how to filter a dictionary to create a new one based on specific criteria for its keys or values. Dictionary comprehensions provide a concise way to achieve this. You can filter by including a whitelist of keys, by applying a condition to the values, or by excluding a blacklist of keys, making it versatile for data selection, transformation, and sanitization within web applications.