字典8大必杀技
🧠 字典热身回顾
字典的本质就是 键值对:
- 键必须唯一且不可变(字符串、数字、元组等)
- 值想放啥就放啥
1 2 3 4 5
| user = { "name": "Alice", "age": 30, "city": "Paris" }
|
🔍 1. get(key[, default]) —— 安全取值不翻车
1 2 3
| print(user.get("age")) # 30 print(user.get("email")) # None print(user.get("email", "N/A")) # N/A
|
✅ 当键不存在时,直接返回 None 或你指定的默认值,程序再也不会因为 KeyError 崩溃。
➕ 2. update(other_dict) —— 一键合并/覆盖
1 2 3
| user.update({"email": "alice@example.com"}) print(user) # {'name': 'Alice', 'age': 30, 'city': 'Paris', 'email': 'alice@example.com'}
|
✅ 同名键会被覆盖,想更新年龄也就一行:
1
| user.update({"age": 31}) # age 从 30 变 31
|
❌ 3. pop(key[, default]) —— 删除并返回值
1 2 3
| age = user.pop("age") print(age) # 31 print(user) # 字典里已没有 'age'
|
如果键不存在,又不想抛错:
1
| email = user.pop("email", "not found")
|
🚫 4. popitem() —— 弹出“最新”键值对(Python 3.7+)
1 2
| last = user.popitem() print(last) # ('email', 'alice@example.com')
|
✅ 把字典当栈用,先进后出。
🧽 5. clear() —— 一键清空
1 2
| user.clear() print(user) # {}
|
🆕 6. setdefault(key[, default]) —— 取不到就创建
1 2 3 4 5 6 7
| settings = {"theme": "dark"}
theme = settings.setdefault("theme", "light") # 已存在,返回 'dark' lang = settings.setdefault("language", "English")# 不存在,新增并返回 'English'
print(settings) # {'theme': 'dark', 'language': 'English'}
|
✅ 初始化嵌套结构时特别香:
1 2 3 4 5
| students = {} students.setdefault("john", {})["math"] = 90 students.setdefault("john", {})["science"] = 85 print(students) # {'john': {'math': 90, 'science': 85}}
|
📋 7. keys() · values() · items() —— 遍历三剑客
1 2 3
| print(user.keys()) # dict_keys(['name', 'city']) print(user.values()) # dict_values(['Alice', 'Paris']) print(user.items()) # dict_items([('name', 'Alice'), ('city', 'Paris')])
|
循环用法:
1 2
| for key, value in user.items(): print(f"{key} = {value}")
|
🔎 8. in 关键字 —— 快速判断键是否存在
1 2
| if "name" in user: print("User has a name")
|
⚠️ 只扫键,不扫值。
🧪 实战 1:单词计数器
1 2 3 4 5 6 7 8
| sentence = "apple banana apple orange banana apple" counts = {}
for word in sentence.split(): counts[word] = counts.get(word, 0) + 1
print(counts) # {'apple': 3, 'banana': 2, 'orange': 1}
|
📄 实战 2:嵌套字典初始化
1 2 3 4 5
| students = {} students.setdefault("john", {})["math"] = 90 students.setdefault("john", {})["science"] = 85 print(students) # {'john': {'math': 90, 'science': 85}}
|
📌 方法速查表
| 方法 |
作用 |
get() |
安全取值,可给默认值 |
update() |
合并或批量更新 |
pop() |
删除并返回值 |
popitem() |
删除并返回最近插入的键值对 |
clear() |
清空字典 |
setdefault() |
取不到就设默认值 |
keys() |
返回所有键的视图 |
values() |
返回所有值的视图 |
items() |
返回所有键值对的视图 |
🧠 今日复盘
- 用
get() 优雅地防 KeyError
- 用
update() 一行合并字典
- 用
pop() / popitem() 精准删除
- 用
setdefault() 轻松初始化嵌套结构
- 用
keys()/values()/items() 高效遍历
https://mp.weixin.qq.com/s/gvNOlw6yldPwTCovVpOKJQ?scene=1