Lesson 12: dict & set comprehension + conditions
The same comprehension idea works for dictionaries and sets too. For a dict you write {key: value for item in sequence} to build a dictionary in one line, and for a set {expression for item in sequence}. As with lists, you can add an if condition to filter.
If a list comprehension produces a list of items, a dict comprehension gives each item a price tag — a key linked to a value. A set comprehension produces a unique collection with no duplicates.
- dict comprehension
- Building a dict in one line: {key: value for item in sequence}.
- set comprehension
- Building a set in one line: {expression for item in sequence}; values are unique.
- comprehension filter
- An if at the end that includes only items meeting the condition — works for dict/set too.