Set and dictionary comprehensions
Not met yet
Curly brackets make the same one-line builder for sets and dictionaries. {name for name in names} builds a set, so repeats vanish. {name: price for name, price in stock} builds a dictionary: the part before the colon is the key, the part after is the value, and if a key comes up twice, the later value wins.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks curly brackets round a comprehension still make a list.
- Thinks a dictionary comprehension keeps every pair when a key repeats. A later pair with the same key replaces the earlier one.