Sometimes, we want to filter a dictionary according to an arbitrary condition function with Python.
In this article, we’ll look at how to filter a dictionary according to an arbitrary condition function with Python.
How to filter a dictionary according to an arbitrary condition function with Python?
To filter a dictionary according to an arbitrary condition function with Python, we can use dict comprehension.
For instance, we write
d = {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
to get the keys and values from the points
dict with items
.
Then we filter the values v
with if v[0] < 5 and v[1] < 5
.
And we return the filter keys and values with k: v
.
Conclusion
To filter a dictionary according to an arbitrary condition function with Python, we can use dict comprehension.