PythonMastery

Filter a dictionary in Python

Keep only the dictionary entries that pass a test, such as scores of 60 or more, using a dict comprehension with an if condition.

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

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.

Learn the idea: Dictionaries, Comprehensions: Lists, Dicts, Sets, Generators