← Back to all snippets
PYTHON

Filter Python Dictionary by Keys or Values

Discover how to create new dictionaries by filtering existing ones based on specific key or value conditions using dictionary comprehensions for clean and efficient code.

data = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York',
    'occupation': 'Engineer',
    'salary': 75000
}

# Filter by keys: keep only specific keys
filtered_by_keys = {k: v for k, v in data.items() if k in ['name', 'age']}
print(f"Filtered by keys ('name', 'age'): {filtered_by_keys}")

# Filter by keys: exclude specific keys
excluded_keys = {'city', 'salary'}
filtered_excluding_keys = {k: v for k, v in data.items() if k not in excluded_keys}
print(f"Filtered excluding keys ('city', 'salary'): {filtered_excluding_keys}")

# Filter by values: keep items where value is a string
filtered_by_value_type = {k: v for k, v in data.items() if isinstance(v, str)}
print(f"Filtered by value type (string): {filtered_by_value_type}")

# Filter by values: keep items where value meets a condition (e.g., age > 25)
filtered_by_value_condition = {k: v for k, v in data.items() if isinstance(v, (int, float)) and v > 25}
print(f"Filtered by value condition (numeric > 25): {filtered_by_value_condition}")
How it works: This snippet demonstrates how to filter a dictionary to create a new one based on specific conditions applied to its keys or values. Dictionary comprehensions provide a concise and Pythonic way to achieve this. You can filter by including or excluding specific keys, or by checking the type or value of the associated data, making it a flexible tool for data manipulation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs