PYTHON

Filter List of Dictionaries by Multiple Conditions

Discover how to filter a list of dictionaries in Python based on multiple, combined criteria using list comprehensions and lambda functions for concise and efficient data filtering.

products = [
    {'id': 1, 'name': 'Laptop', 'category': 'Electronics', 'price': 1200, 'in_stock': True},
    {'id': 2, 'name': 'Keyboard', 'category': 'Electronics', 'price': 75, 'in_stock': False},
    {'id': 3, 'name': 'Monitor', 'category': 'Electronics', 'price': 300, 'in_stock': True},
    {'id': 4, 'name': 'Desk Chair', 'category': 'Furniture', 'price': 150, 'in_stock': True},
    {'id': 5, 'name': 'USB Hub', 'category': 'Electronics', 'price': 30, 'in_stock': True}
]

# Filter products that are 'Electronics' AND 'in_stock' AND 'price' < 500
filtered_products = [
    product for product in products
    if product['category'] == 'Electronics'
    and product['in_stock']
    and product['price'] < 500
]

print("Products matching all criteria:")
for p in filtered_products:
    print(p)

# Filter products using filter() with a lambda function for OR conditions
# Products that are 'Furniture' OR 'price' < 100
filtered_with_lambda = list(filter(lambda p: p['category'] == 'Furniture' or p['price'] < 100, products))

print("
Products matching 'Furniture' OR price < 100:")
for p in filtered_with_lambda:
    print(p)
How it works: Filtering a list of dictionaries based on multiple conditions is a common task in web development, especially when processing API responses or database query results. This snippet demonstrates two powerful methods: list comprehensions and the `filter()` function with a `lambda`. List comprehensions offer a concise and readable way to create new lists by iterating over existing ones and applying conditional logic (using `if` clauses and `and`/`or` operators). The `filter()` function, combined with a `lambda` function, provides an alternative, functional approach, returning an iterator that yields items for which the lambda returns true. Both methods are efficient and Pythonic for data subsetting.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs