Paul's Python CoursePPC

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.py
sales = [("apples", 45), ("kale", 150), ("apples", 45)]
sold = {name for name, price in sales}
prices = {name: price for name, price in sales}
print(sorted(sold))
print(prices)

Output

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.

Where it comes up