Night 18: Your pet's ID card
你已使用 Python 或伪代码完成过这个夜间练习,两种语言均计入完成记录。你可以再次练习。
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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 |
English
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" |

English
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 |
English
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)
English
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!
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Make a dictionary pet with three keys: "name" is(是) "Kit", "age" is(是) 2, "food" is(是) "fish". Print the pet's name.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
It is Kit's birthday! Add 1 to pet["age"]. Then print the new age: 3.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Kit has a new toy. Add the key "toy" with the value "ball". Then print Kit plays with ball, using the dictionary.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Read a key with input(). If the key is in pet, print its value. If not, print No such thing.
点击“运行”查看此处输出。