🗂️ Dictionaries & Sets, lesson 1 of 5
Dictionaries: look things up by key
Map keys to values, like a phone book or a price list.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
A dictionary (dict) maps keys to
values, like a menu maps dishes to prices. You
find a value by its key, not by its position:
prices = {"apple": 0.5, "bread": 2.25}
prices["bread"] # 2.25
Keys are unique. Assigning to a key adds it if it's new, or replaces its value if it exists.
A price list
Add a price for "coffee", then print just that price.
Asking for a key that isn't there raises a KeyError. Two safe ways to look things up:
key in dchecks whether a key exists.d.get(key, default)returns the default (orNone) instead of crashing.
KeyError
Dictionary keys are case-sensitive too: stock["Apples"] fails the same way.
.get() to the rescue
in checks keys, not values. Pears are in the
dictionary even though there are 0 of them.
What does this print?
Remove a key with del d[key], or with
d.pop(key), which also returns the value.
Contacts
What happens if you del a name that isn't there?
Which of these can NOT be used as a dictionary key?
Update the inventory
Update inventory:
- Add
"cherries"with a count of 30. - You sold 2 bananas: subtract 2 from its count.
- Remove
"apples"completely. - Set
grapesto the grape count using.get()with a default of 0.