Dictionaries
A dictionary stores pairs.
Each pair has a key and a value.
Think of labeled drawers. The key is the label. The value is what is inside.
You look up by the label, not by a shelf number.
Creating a dictionary
Use curly braces.
Write key: value, then a comma, then the next pair.
Adding and changing
Assign to a key.
If the key is new, Python adds it.
If the key exists, Python replaces the value.
Safe lookup
user['missing'] can crash if the key is not there.
Use get to ask gently.
get can also give a default if the key is missing.
Removing pairs
pop removes a key and returns its value.
del can remove a key too.
Keys, values, and items
You can walk through the drawers in a loop.
keys() gives the labels
values() gives what is inside
items() gives both together
Checking for a key
Use in to ask if a label exists.
Tip: Keys must be unique. Pick clear key names, like drawer labels you can read.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.