How to filter a dictionary according to an arbitrary condition function with Python?

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 dictionary comprehension.

For instance, we write:

points = {'a': (3, 4), 'b': (1, 2), 'c': (5, 5), 'd': (3, 3)}
new_points = {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
print(new_points)

We define the points dictionary and we want to return a new dictionary with the tuples entries all less than 5.

To do this, we write:

new_points = {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}

v is the dictionary entry’s value being looped through, which is the tuple.

We assign that to new_points and we get that it’s:

{'a': (3, 4), 'b': (1, 2), 'd': (3, 3)}

Conclusion

To filter a dictionary according to an arbitrary condition function with Python, we can use dictionary comprehension.