Night 18: Your pet's ID card
Bạn đã hoàn thành đêm này bằng Python hoặc mã giả. Kết quả được tính cho cả hai. Bạn có thể luyện tập lại nếu muốn.
Tonight: your pet's ID card
- Your pet needs an ID card with its name, age and food.
- You will learn one thing: dictionaries.
Words for tonight
| Word | Meaning |
|---|---|
| dictionary | a set of keys, each with a value |
| key | the name you look up, like "age" |
| value | what is stored for a key, like 2 |
Make a dictionary
- Use
{ }. Writekey: valuepairs, with commas between them.
pet = {"name": "Kit", "age": 2, "food": "fish"}
print(pet["name"])
print(pet["food"])
| Key | Value |
|---|---|
"name" |
"Kit" |
"age" |
2 |
"food" |
"fish" |

List or dictionary?
| List | Dictionary |
|---|---|
["Kit", 2, "fish"] |
{"name": "Kit", "age": 2, "food": "fish"} |
find by position: pet[1] |
find by key: pet["age"] |
| good for many things of one kind | good for many facts about one thing |
Change and add
- Use the key in
[ ]with=to change a value, or to add a new key.
pet = {"name": "Kit", "age": 2}
pet["age"] = 3
pet["toy"] = "ball"
print(pet)
Is the key there?
inchecks if a dictionary has a key.
pet = {"name": "Kit", "age": 2}
if "toy" in pet:
print(pet["toy"])
else:
print("No toy yet")
- Now make your pet's ID card!
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Make a dictionary pet with three keys: "name" là (is) "Kit", "age" là (is) 2, "food" là (is) "fish". Print the pet's name.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
It is Kit's birthday! Add 1 to pet["age"]. Then print the new age: 3.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Kit has a new toy. Add the key "toy" with the value "ball". Then print Kit plays with ball, using the dictionary.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Read a key with input(). If the key is in pet, print its value. If not, print No such thing.
Nhấn Chạy để xem kết quả ở đây.