Course contentsShow
← Python
Lesson 238 of 1,0604. Data Structures MasteryFree lesson

Filtering Nested Collections with List Comprehensions

You will apply conditional logic within nested comprehensions to extract and transform specific data points from multi-layered dictionaries and lists.

In this lesson, you will learn how to combine nested loops and conditional statements within a single list comprehension to extract specific items from complex, multi-layered data structures.

The Power of "Filter-in-a-Nested-Loop"

When dealing with a list of dictionaries—like a list of users, where each user has a list of "orders"—standard loops can become verbose. A nested list comprehension allows you to flatten this hierarchy while simultaneously applying a filter to ignore data that doesn't meet your criteria.

Think of it as a pipeline: you reach into the outer collection, dive into the inner collection, and only "keep" the items that satisfy your if condition.

Concrete Example

Imagine we have a collection of store departments, each containing a list of products. We want to extract the names of all products that cost more than $50.

store_data = [
    {"dept": "Electronics", "items": [{"name": "Laptop", "price": 800}, {"name": "Mouse", "price": 20}]},
    {"dept": "Home", "items": [{"name": "Blender", "price": 60}, {"name": "Spoon", "price": 5}]}
]

# Extracting expensive items using a nested comprehension
expensive_items = [
    item["name"] 
    for dept in store_data 
    for item in dept["items"] 
    if item["price"] > 50
]

print(expensive_items) 
# Output: ['Laptop', 'Blender']

Breaking Down the Syntax

  1. for dept in store_data: The outer loop iterates through each dictionary in our main list.
  2. for item in dept["items"]: The inner loop drills down into the nested list of items.
  3. if item["price"] > 50: This acts as a gatekeeper. Only items that pass this condition are processed by the expression at the very start (item["name"]).

By structuring the comprehension this way, you avoid writing multiple for loops and if statements, resulting in cleaner, more readable code that expresses your intent in a single, declarative line. As long as your logic remains relatively simple, this approach is the most efficient way to transform and filter nested data structures in Python.

Key Takeaway: Nested list comprehensions use a sequence of for clauses to traverse depth, followed by an if clause to prune unwanted elements, allowing you to transform multi-layered data into a flat, filtered list in one operation.