To filter a dictionary, build a new one that has only the pairs that pass your test. A dict comprehension with an if at the end does this in one line.
The program
python
scores = {"Ada": 85, "Linus": 42, "Grace": 91, "Alan": 58, "Hedy": 60}
passed = {name: score for name, score in scores.items() if score >= 60}
failed = {name: score for name, score in scores.items() if score < 60}
print("Passed:", passed)
print("Failed:", failed)output
Passed: {'Ada': 85, 'Grace': 91, 'Hedy': 60}
Failed: {'Linus': 42, 'Alan': 58}How it works
- The comprehension loops over every
(name, score)pair. Theif score >= 60part skips the pairs that fail the test. >=includes 60 itself, so Hedy passes. Check the boundary value whenever you write a condition like this.- The original
scoresdictionary is not changed.
Filtering by key
The test can use the key, the value, or both:
python
prices = {"apple": 1.20, "avocado": 2.50, "banana": 0.40, "apricot": 3.10}
a_fruits = {fruit: p for fruit, p in prices.items() if fruit.startswith("a")}
print(a_fruits)
cheap_a = {fruit: p for fruit, p in prices.items() if fruit.startswith("a") and p < 3}
print(cheap_a)output
{'apple': 1.2, 'avocado': 2.5, 'apricot': 3.1}
{'apple': 1.2, 'avocado': 2.5}Do not delete keys from a dictionary while you loop over it: Python raises RuntimeError: dictionary changed size during iteration. Building a new dictionary, as above, avoids that problem.