How to Filter Query Parameters by Operator in Python

Parse a URL query string and keep only parameters with allowed comparison operators like eq, gt, and lt.

Medium Python 3.9+ Aug 9, 2026 API design & gRPC 12 views 0 copies

Python code

19 lines
Python 3.9+
from urllib.parse import urlparse, parse_qs

def filter_operators(query_string, allowed=("eq", "gt", "lt")):
    parsed = urlparse(query_string)
    params = parse_qs(parsed.query)
    filtered = {}
    for key, values in params.items():
        if "__" in key:
            field, op = key.rsplit("__", 1)
            if op in allowed:
                filtered[key] = values[0]
        else:
            filtered[key] = values[0]
    return filtered

if __name__ == "__main__":
    query = "price__gt=100&category=books&price__gte=50&in_stock=true"
    result = filter_operators(query)
    print(result)

Output

stdout
{'price__gt': '100', 'category': 'books', 'in_stock': 'true'}

How it works

The urlparse call breaks the query string into its components, and parse_qs converts it into a dictionary of lists. The function iterates over each key, checks if it contains double underscores to indicate an operator, and extracts the operator as everything after the last __. It then verifies the operator is in the allowed set and only keeps the first value if so. This pattern is common in API request handling to allow clients to specify comparisons while preventing unsupported operators from being processed.

Common mistakes

  • Using split('__') on the whole key instead of rsplit with maxsplit=1, which breaks fields with underscores.
  • Forgetting that parse_qs returns lists, causing TypeError when treating values as strings.
  • Not handling keys without __ (simple equality filters) and skipping them entirely.

Variations

  1. Use a regex like `(?P<field>.*)__(?P<op>eq|gt|lt)` to extract fields and operators.
  2. Return a structured dict like `{'field': 'price', 'operator': 'gt', 'value': '100'}` instead of keeping the combined key.

Real-world use cases

  • Building a REST API where GET endpoints accept comparators such as `?age__gt=21`.
  • Creating a query builder for a database ORM to translate URL filters into SQL WHERE clauses.
  • Implementing an internal tool to sanitize and validate user-supplied filter parameters before execution.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.