Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
57: Set and Dictionary Comprehensions
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"}).
There are no comments for now.