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.
Python code
19 linesfrom 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
{'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
- Use a regex like `(?P<field>.*)__(?P<op>eq|gt|lt)` to extract fields and operators.
- 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
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.