Python Practice › Dictionary Programs › Program 71
Keep even numbers in list values
Write a Python program to keep only even numbers in each list value.
Input
{"a": [11, 4, 6, 15], "b": [3, 8, 12], "c": [5, 3, 10]}Output
{'a': [4, 6], 'b': [8, 12], 'c': [10]}Approach
- Nested comprehensions.
Solution
d = {"a": [11, 4, 6, 15], "b": [3, 8, 12], "c": [5, 3, 10]}print({k: [x for x in v if x % 2 == 0] for k, v in d.items()})Output
{'a': [4, 6], 'b': [8, 12], 'c': [10]}Learn the concept
New to this topic? Read the lesson, then come back.