此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
按名字存放数据
- 字典(dictionary)把值存放在叫作键(key)的名字下。
- 把键值对写在花括号里:
{"name": "Sam", "age": 15}。 - 每个键都是唯一的,指向一个值。
读取和设置值
- 用键来读取值:
person["name"]。 - 用同样的方式添加或修改值:
person["age"] = 16。 - 列表用数字索引;字典用键。
English
ages = {"Sam": 12, "Mia": 15}
print(ages["Sam"])
ages["Leo"] = 9
print(ages)
用字典表示记录
- 记录(record)把关于某一事物的相关信息组合在一起。
- 字典是保存一条记录的简便方式。
- 每个键就是一个字段(field),例如
name或grade。
English
pupil = {"name": "Ada", "grade": "A"}
print(pupil["name"])
print(pupil["grade"])
判断和遍历
- 如果某个键存在,
"name" in person就是True。 for key in person:会依次访问每个键。- 如果键不存在,
person.get("x", 0)会返回一个默认值。
English
menu = {"tea": 2, "cake": 5}
for item in menu:
print(item, menu[item])
print("tea" in menu)
用剑桥伪代码表示
- 字典对应考试里的
TYPE记录;每个键就是一个字段,用点号来访问。
TYPE Student
DECLARE Name : STRING
DECLARE Age : INTEGER
ENDTYPE
DECLARE Pupil : Student
Pupil.Name ← "Sam"
Pupil.Age ← 15
常见错误
- 用键读取值:
d["name"];键不存在会抛出 KeyError。 - 键是唯一的——给同一个键再赋值会覆盖旧值。
- 键可能不存在时,用
d.get(key)。
现在轮到你
- 每个任务都要构建或更新一个字典。
- 按检查答案来测试你的代码。
探索
Look up by key
A dictionary jumps straight to the value for a key — no scanning.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Create a dictionary book with two keys: title set to "Python" and pages set to 200.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
The dictionary student already has name and score. Change score 到 85, and add a new key passed set to True.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Loop over the dictionary prices and add up its values. Store the total in total (the answer is 10).
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Write count_words(text) that 返回值 a dictionary: each word of text (split on spaces) mapped to how many times it appears. count_words("the cat and the hat") gives {"the": 2, "cat": 1, "and": 1, "hat": 1}.
点击“运行”查看此处输出。