PYTHON

Filter a List of Dictionaries by Condition

Discover how to efficiently filter a list of Python dictionaries based on specific criteria, a vital skill for processing and displaying relevant data in web applications.

products = [
    {'id': 1, 'name': 'Laptop', 'price': 1200, 'category': 'Electronics'},
    {'id': 2, 'name': 'Mouse', 'price': 25, 'category': 'Electronics'},
    {'id': 3, 'name': 'Keyboard', 'price': 75, 'category': 'Electronics'},
    {'id': 4, 'name': 'Book', 'price': 20, 'category': 'Books'},
    {'id': 5, 'name': 'Monitor', 'price': 300, 'category': 'Electronics'}
]

# Filter products with price > 100
expensive_products = [p for p in products if p['price'] > 100]
# print(expensive_products)
# [{'id': 1, 'name': 'Laptop', 'price': 1200, 'category': 'Electronics'},
#  {'id': 5, 'name': 'Monitor', 'price': 300, 'category': 'Electronics'}]

# Filter products in 'Electronics' category
electronics_products = list(filter(lambda p: p['category'] == 'Electronics', products))
# print(electronics_products)
# [{'id': 1, 'name': 'Laptop', 'price': 1200, 'category': 'Electronics'},
#  {'id': 2, 'name': 'Mouse', 'price': 25, 'category': 'Electronics'},
#  {'id': 3, 'name': 'Keyboard', 'price': 75, 'category': 'Electronics'},
#  {'id': 5, 'name': 'Monitor', 'price': 300, 'category': 'Electronics'}]

# Filter products with price between 50 and 500
mid_range_products = [p for p in products if 50 <= p['price'] <= 500]
# print(mid_range_products)
# [{'id': 3, 'name': 'Keyboard', 'price': 75, 'category': 'Electronics'},
#  {'id': 5, 'name': 'Monitor', 'price': 300, 'category': 'Electronics'}]
How it works: This snippet illustrates how to filter a list of dictionaries based on one or more conditions applied to their values. It demonstrates two common Pythonic approaches: list comprehensions and the `filter()` built-in function. List comprehensions offer a concise and readable way to create new lists by iterating and applying conditions. The `filter()` function, combined with a `lambda` function, provides an alternative for applying a predicate function to each item, returning an iterator that needs to be converted to a list.

Need help integrating this into your project?

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

Hire DigitalCodeLabs