PYTHON

Filter a List of Objects by Attribute Value in Python

Discover how to efficiently filter a list of custom objects or dictionaries based on specific attribute values using Python's list comprehensions for dynamic data selection.

class Product:
    def __init__(self, name, category, price):
        self.name = name
        self.category = category
        self.price = price

    def __repr__(self):
        return f"Product('{self.name}', '{self.category}', {self.price})"

products = [
    Product('Laptop', 'Electronics', 1200),
    Product('Mouse', 'Electronics', 25),
    Product('Keyboard', 'Peripherals', 75),
    Product('Monitor', 'Electronics', 300),
    Product('Webcam', 'Peripherals', 50),
]

# Filter products by category 'Electronics'
electronics_products = [p for p in products if p.category == 'Electronics']
print(f"Electronics Products: {electronics_products}")

# Filter products with price less than 100
affordable_products = [p for p in products if p.price < 100]
print(f"Affordable Products: {affordable_products}")

# Filter products by multiple conditions
filtered_by_multiple = [p for p in products if p.category == 'Peripherals' and p.price > 60]
print(f"Peripherals > $60: {filtered_by_multiple}")
How it works: This snippet shows how to filter a list of objects based on one or more attribute conditions using Python's powerful list comprehensions. It's an elegant and efficient way to select specific items from a collection, similar to database queries, making it indispensable for processing data retrieved from APIs, databases, or user input in web applications where precise data filtering is often required.

Need help integrating this into your project?

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

Hire DigitalCodeLabs