Python filter
built-in function allows filtering Python iterables by function that shall return True/False. The problem with it ,that you can easily pass a query to that function to filter the iterable.
Example of Python filter
def filter_age(item):
return item["age"] > 19
l = [{"name":"John","age":16}, {"name":"Mike","age":19},{"name":"Sarah","age":21}]
print(list(filter(filter_age,l)))
output
[{'name': 'Sarah', 'age': 21}]
What if you want to pass the age as parameter to filter_age
function. This will need a partial which isn't complex but isn't comprehensive enough.
Leopards
Leopards is a Python library that provides an easy and fast way to filter members of a list or a tuple. The member can be a dict or object. The library supports AND, OR and NOT implementations.
Example
from leopards import Q
l = [{"name":"Karen","age":"16"}, {"name":"Mike","age":"19"},{"name":"Sarah","age":"21"}]
filtered= Q(l,{'name__icontains':"k", "age__gt":16})
print(list(filtered))
output
[{'name': 'Mike', 'age': '19'}]
For more examples and how to install/ use the library. Please check the github repo.
Leopards
Leopards is a way to query list of dictionaries or objects as if you are filtering in DBMS You can get dicts/objects that are matched by OR, AND or NOT or all of them As you can see in the comparison they are much faster than Pandas.
Installation
pip install leopards
Usage
from leopards import Q
l = [{"name":"John","age":"16"}, {"name":"Mike","age":"19"},{"name":"Sarah","age":"21"}]
filtered= Q(l,{'name__contains':"k", "age__lt":20})
print(list(filtered))
output
[{'name': 'Mike', 'age': '19'}]
The above filtration can be written as
from leopards import Q
l = [{"name": "John", "age": "16"}, {"name": "Mike", "age": "19"}, {"name": "Sarah"
…Happy Coding.
Top comments (0)