PYTHON
Filtering a List of Dictionaries by Multiple Criteria
Efficiently filter a list of Python dictionaries based on multiple conditions using list comprehensions, a powerful technique for implementing search and filtering features in web applications.
products = [
{"id": 1, "name": "Laptop", "category": "Electronics", "price": 1200},
{"id": 2, "name": "Desk Chair", "category": "Furniture", "price": 300},
{"id": 3, "name": "Mouse", "category": "Electronics", "price": 25},
{"id": 4, "name": "Monitor", "category": "Electronics", "price": 400},
{"id": 5, "name": "Bookshelf", "category": "Furniture", "price": 150},
]
# Filter products: category 'Electronics' AND price < 500
filtered_electronics = [
product for product in products
if product['category'] == 'Electronics' and product['price'] < 500
]
# Filter products: category 'Furniture' OR price > 1000
filtered_furniture_or_expensive = [
product for product in products
if product['category'] == 'Furniture' or product['price'] > 1000
]
# print("Electronics under $500:")
# for product in filtered_electronics:
# print(product)
# print("
Furniture OR expensive (> $1000):")
# for product in filtered_furniture_or_expensive:
# print(product)
How it works: This snippet demonstrates how to filter a list of dictionaries based on multiple conditions using Python list comprehensions. This concise and readable syntax allows you to build a new list containing only the dictionaries that satisfy all specified criteria (using `and`) or any of the criteria (using `or`). This technique is fundamental for implementing search functionality, applying filters to displayed data, or processing subsets of data within web applications.