DEV Community

Mohamed M El-Kalioby
Mohamed M El-Kalioby Subscriber

Posted on • Edited on

2

Filter🐍 Python Iterables by Complex Queries

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)))
Enter fullscreen mode Exit fullscreen mode

output

[{'name': 'Sarah', 'age': 21}]
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

output

[{'name': 'Mike', 'age': '19'}]
Enter fullscreen mode Exit fullscreen mode

For more examples and how to install/ use the library. Please check the github repo.

GitHub logo mkalioby / leopards

Query your python lists

Leopards

PyPI version Python Versions Coverage build status

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
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

output

[{'name': 'Mike', 'age': '19'}]
Enter fullscreen mode Exit fullscreen mode

The above filtration can be written as

from leopards import Q
l = [{"name": "John", "age": "16"}, {"name": "Mike", "age": "19"}, {"name": "Sarah"
Enter fullscreen mode Exit fullscreen mode

Happy Coding.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay