Set comprehensions
A set comprehension builds a set from another collection in one line, with no duplicates.
Used in 22 lessons of the course, from 00.04.
A set comprehension looks like {expression for name in collection}. Python walks the collection, computes the expression for each item, and stores the results in a set. Because a set holds no duplicates, each value appears once, and the order is not guaranteed.
You can add a filter at the end with if: only items that pass it get in.
The shape matches a list comprehension, but with curly braces and no key: value pairs. If there were pairs, it would be a dict comprehension.
The course uses it like this: present = {k for k, v in dotenv_values(actual).items() if v}. It walks key-value pairs, keeps the keys whose value is not empty, and gathers them into a set. With a set you can quickly ask whether a key is present.
Watch out: an empty {} is a dict, not a set. For an empty set use set().
Reach for it when: you need the unique values of something, or a set of keys for membership checks, filtering or transforming as you build it.
Examples
Common mistake
empty = {x for x in []}
other = {}
print(type(empty).__name__, type(other).__name__)Why: Empty braces `{}` create a dict, not a set. It is easy to expect a set.
How to write it: For an empty set write set().
