Lesson ยท 12 min
Dictionaries
Values with names
A list keeps values in order, and you find them by position. A dictionary keeps values with keys, and you find a value by its key. Each key with its value is a pair.
pet = {
"name": "Biscuit",
"age": 4,
"is_friendly": True,
}
Reading and changing
Use square brackets with the key.
print(pet["name"]) # Biscuit
pet["age"] = 5 # change a value
pet["color"] = "brown" # add a new pair
If you ask for a key that does not exist, Python stops with a KeyError. The get method is safer. It gives None, or a default value that you choose.
print(pet.get("weight")) # None
print(pet.get("weight", "unknown")) # unknown
Useful tools
"name" in petisTruewhen the key exists.pet.keys()gives the keys,pet.values()gives the values, andpet.items()gives the pairs.len(pet)is the number of pairs.
for key, value in pet.items():
print(key, value)
Dictionaries inside lists
Most real data is a list of dictionaries. For example, a list of books, users, or products.
pets = [
{"name": "Biscuit", "age": 4},
{"name": "Pepper", "age": 2},
]
for pet in pets:
print(pet["name"], "is", pet["age"])
Your turn
The dictionary book is already in the editor. Write your code under it. The tasks build on each other, so do them in order.
Tasks
6 to do
Task 1, not checked yet. Add a key named
authortobook. Its value is the textTobias Lind.Task 2, not checked yet. Change the value of
pagesto224.Task 3, not checked yet. Make a variable
summarywith the textSmall Engines by Tobias Lind (224 pages). Build it with an f-string that reads the values frombook.Task 4, not checked yet. Make a variable
yearwith the value of the keyyearfrombook. The key does not exist, so use thegetmethod with the default value'unknown'.Task 5, not checked yet. Make a variable
library. It is a list with two items:book, and a second dictionary withtitleset toNight Trainsandpagesset to188.Task 6, not checked yet. Use a loop to print the
titleof each item inlibrary, one on each line.
Task 1 of 6
Add a key named author to book. Its value is the text Tobias Lind.