python · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Curly brackets make a dict or .
Swap the square brackets for curly ones and you can build a dictionary instead. A needs a key and a value with a colon between them: {name: len(name) for name in names}.
Loop over .items() to build one dictionary from another, for example turning pence into pounds, or keeping only the stock that is running low.
Leave out the colon and you get a set comprehension. Sets keep no repeats, so {tag.lower() for tag in tags} tells you which different tags appeared.
stock = {"apples": 40, "pears": 3, "plums": 0}
low = {fruit: count for fruit, count in stock.items() if count < 5}
tags = ["Python", "python", "SQL", "sql", "Go"]
unique = {tag.lower() for tag in tags}
print(low)
print(sorted(unique)) A set has no order, so sorted hands its items back as a list in order.
guess first
Ana changed her mind. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
votes = [("Ana", "pizza"), ("Ben", "curry"), ("Ana", "tacos")]
latest = {name: food for name, food in votes}
print(latest)
your turn
Your turn. Build a price list in pounds.
Fill the blanks so each item keeps its name and its price is divided by 100. Then add a drink of your own to pence if you like.
fix it
There are three different pages, not five. Fix it!
- Count the different pages by hand. Which kind of collection keeps no repeats?
- Square brackets build a list, and a list keeps every repeat.
- Change the square brackets on line 2 to curly ones, then run.
nailed it
you can build dictionaries and sets in one go. :D
{key: value for ...}builds a dictionary.{value for ...}builds a set with no repeats.- Loop over
.items()to reshape one dictionary into another.
new words in your collection
- dict comprehension
- set comprehension
This lesson isn’t saved. A free account remembers every lesson you finish.