How to Filter Dictionary by Key in Python: Simple Guide
To filter a dictionary by key in Python, use
dictionary comprehension with a condition on keys, like {k: v for k, v in my_dict.items() if k in keys_to_keep}. This creates a new dictionary containing only the keys you want.Syntax
The basic syntax to filter a dictionary by key uses dictionary comprehension:
{key: value for key, value in original_dict.items() if condition_on_key}Here:
original_dict.items()gives pairs of keys and values.key: valuebuilds the new dictionary entries.if condition_on_keyfilters keys based on your condition.
python
{k: v for k, v in original_dict.items() if k in keys_to_keep}Example
This example shows how to keep only certain keys from a dictionary.
python
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3, 'date': 4}
keys_to_keep = {'banana', 'date'}
filtered_dict = {k: v for k, v in my_dict.items() if k in keys_to_keep}
print(filtered_dict)Output
{'banana': 2, 'date': 4}
Common Pitfalls
Common mistakes when filtering dictionaries by key include:
- Using
dict.keys()without.items(), which gives keys only, not key-value pairs. - Modifying the dictionary while iterating over it, which causes errors.
- Forgetting that dictionary comprehension creates a new dictionary, so the original stays unchanged.
python
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Wrong: trying to filter keys without items()
# filtered = {k: my_dict[k] for k in my_dict.keys() if k == 'a'} # Works but less efficient
# Right: use items() for direct access
filtered = {k: v for k, v in my_dict.items() if k == 'a'}
print(filtered)Output
{'a': 1}
Quick Reference
Tips for filtering dictionaries by key:
- Use dictionary comprehension with
.items()for clean and efficient filtering. - Check if keys match your condition inside the
ifclause. - Remember the original dictionary is not changed; you get a new filtered dictionary.
Key Takeaways
Use dictionary comprehension with .items() to filter by key efficiently.
The condition inside the comprehension controls which keys to keep.
Filtering creates a new dictionary; the original stays unchanged.
Avoid modifying a dictionary while iterating over it.
Check your key condition carefully to avoid unexpected results.