Skip to Content
Course content

57: Set and Dictionary Comprehensions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you're probably comfortable with list comprehensions. They're a Python staple. But the beauty of this syntax is that it isn't limited to lists. We can use the exact same "compressed" logic to build dictionaries and sets, which is incredibly useful when you're transforming raw data into something your application can actually use.

Let's say we're building a small inventory system for a hobby shop. We have a list of product dictionaries, and we need to do two things: create a quick-lookup map for product names and generate a list of all unique categories available for a filter menu.

products = [
    {"id": 101, "name": "Soldering Iron", "category": "Tools", "price": 25.00},
    {"id": 102, "name": "Solder Wire", "category": "Consumables", "price": 12.00},
    {"id": 103, "name": "Multimeter", "category": "Tools", "price": 45.00},
    {"id": 104, "name": "Heat Shrink", "category": "Consumables", "price": 8.00},
    {"id": 105, "name": "Breadboard", "category": "Prototyping", "price": 15.00},
]

Mapping IDs to Names

First, I want a dictionary where the keys are the product IDs and the values are the names. I could write a for loop and initialize an empty dict, but that's just more boilerplate than we need. Instead, I'll use a dictionary comprehension. The syntax is almost identical to a list comprehension, but we wrap it in curly braces and define a key-value pair.

# {key: value for item in iterable}
product_lookup = {p["id"]: p["name"] for p in products}

print(product_lookup) 
# Output: {101: 'Soldering Iron', 102: 'Solder Wire', 103: 'Multimeter', ...}

This is clean. I've effectively transformed a list of objects into a high-speed lookup table in a single line.

The "Duplicate" Trap

Now, I want to get a list of all the categories. My first instinct—and this is a mistake I've made plenty of times when rushing—is to try and use a dictionary comprehension again because I'm already in that headspace.

# My mistake: trying to use a dict for unique categories
categories_dict = {p["category"]: True for p in products}
# Result: {'Tools': True, 'Consumables': True, 'Prototyping': True}

While this technically works to get unique keys, it's awkward. I'm adding a useless True value to every entry just to force uniqueness. I don't actually want a mapping; I just want a collection of unique strings. This is where set comprehensions come in.

Extracting Unique Categories

A set comprehension looks exactly like a dictionary comprehension, but without the colon. It tells Python: "Iterate through this, grab this one value, and throw it into a set." Since sets automatically discard duplicates, it's the perfect tool for this.

# {value for item in iterable}
unique_categories = {p["category"] for p in products}

print(unique_categories)
# Output: {'Tools', 'Consumables', 'Prototyping'}

I love how explicit this is. If another developer sees {...} without a colon, they know immediately that they're looking at a set. It's much more intentional than writing list(set([p["category"] for p in products])), which is a bit of a mouthful.

Adding a Condition to the Mix

Just like with lists, we can add an if statement to the end. Let's say we only want the lookup map for products that cost more than $10. We just tack that condition onto the end of our dictionary comprehension.

expensive_products = {p["id"]: p["name"] for p in products if p["price"] > 10}

print(expensive_products)
# Output: {101: 'Soldering Iron', 102: 'Solder Wire', 103: 'Multimeter', 105: 'Breadboard'}

The "Heat Shrink" was dropped because it was too cheap. Simple, readable, and efficient.




📋 Practical Task

Build a User Role Permission Map

You are given a list of user records. Each record contains a username and a list of roles they belong to. Your goal is to create a dictionary comprehension that maps each username to the number of roles they have, but only for users who have at least one role.

Additionally, create a set comprehension that extracts every single unique role mentioned across the entire dataset.

users = [
    {"username": "alice", "roles": ["admin", "editor"]},
    {"username": "bob", "roles": ["viewer"]},
    {"username": "charlie", "roles": []},
    {"username": "dan", "roles": ["editor", "viewer", "moderator"]},
    {"username": "eve", "roles": []},
]

Requirements:

  • The resulting dictionary should look like: {"alice": 2, "bob": 1, ...} (Charlie and Eve should be excluded).
  • The resulting set should contain all unique roles (e.g., {"admin", "editor", "viewer", "moderator"}).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.