Chapter 09 ยท Collections
Dictionaries
A list is great when order matters. But sometimes you want to look things up by a label, not a position - a phone book, a price list, a student's record. That's a dictionary.
A dictionary is a real dictionary: you look up a word (the key) and get its meaning (the value). You don't care if "zebra" is item number 4,000 โ you look it up by name, instantly.
Making a dictionary
Curly braces, with key: value pairs:
student = {
"name": "Grace",
"age": 19,
"course": "Computer Science"
}
print(student["name"])
print(student["course"])
You look things up by their key (student["name"]), not by a number.
Adding and changing
prices = {"bread": 25, "milk": 18}
prices["eggs"] = 40
prices["bread"] = 30
print(prices)
print("Eggs now cost K", prices["eggs"])
Assigning to a new key adds it; assigning to an existing key updates it.
Looping over a dictionary
prices = {"bread": 30, "milk": 18, "eggs": 40}
for item in prices:
print(f"{item} costs K{prices[item]}")
Build a dictionary describing you: keys for name, town and age.
Print a sentence about yourself using the values.
Asking for a key that isn't there (prices["sugar"] when there's no sugar) causes an error.
You can check first with if "sugar" in prices:.
Recap
- A dictionary stores key: value pairs in
{ }. - Look up and set values by key:
d["name"]. - Perfect for records and lookups where a label makes more sense than a position.