苦练Python第26天:精通字典8大必杀技
前言
大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
现在我们已经把字典的基本概念摸得门儿清,今天继续升级,把字典的“隐藏技能”一次点满,让你成为真正的 字典忍者!🥷🐍
📦 今日收获清单
- 掌握
get()
、update()
、pop()
等高频方法学会安全取值、合并字典、优雅删改配合真实场景,即学即用🧠 字典热身回顾
字典的本质就是 键值对:
- 键必须唯一且不可变(字符串、数字、元组等)值想放啥就放啥
user = { "name": "Alice", "age": 30, "city": "Paris"}
🔍 1. get(key[, default])
—— 安全取值不翻车
print(user.get("age")) # 30print(user.get("email")) # Noneprint(user.get("email", "N/A")) # N/A
✅ 当键不存在时,直接返回 None
或你指定的默认值,程序再也不会因为 KeyError
崩溃。
➕ 2. update(other_dict)
—— 一键合并/覆盖
user.update({"email": "alice@example.com"})print(user)# {'name': 'Alice', 'age': 30, 'city': 'Paris', 'email': 'alice@example.com'}
✅ 同名键会被覆盖,想更新年龄也就一行:
user.update({"age": 31}) # age 从 30 变 31
❌ 3. pop(key[, default])
—— 删除并返回值
age = user.pop("age")print(age) # 31print(user) # 字典里已没有 'age'
如果键不存在,又不想抛错:
email = user.pop("email", "not found")
🚫 4. popitem()
—— 弹出“最新”键值对(Python 3.7+)
last = user.popitem()print(last) # ('email', 'alice@example.com')
✅ 把字典当栈用,先进后出。
🧽 5. clear()
—— 一键清空
user.clear()print(user) # {}
🆕 6. setdefault(key[, default])
—— 取不到就创建
settings = {"theme": "dark"}theme = settings.setdefault("theme", "light") # 已存在,返回 'dark'lang = settings.setdefault("language", "English")# 不存在,新增并返回 'English'print(settings)# {'theme': 'dark', 'language': 'English'}
✅ 初始化嵌套结构时特别香:
students = {}students.setdefault("john", {})["math"] = 90students.setdefault("john", {})["science"] = 85print(students)# {'john': {'math': 90, 'science': 85}}
📋 7. keys()
· values()
· items()
—— 遍历三剑客
print(user.keys()) # dict_keys(['name', 'city'])print(user.values()) # dict_values(['Alice', 'Paris'])print(user.items()) # dict_items([('name', 'Alice'), ('city', 'Paris')])
循环用法:
for key, value in user.items(): print(f"{key} = {value}")
🔎 8. in
关键字 —— 快速判断键是否存在
if "name" in user: print("User has a name")
⚠️ 只扫键,不扫值。
🧪 实战 1:单词计数器
sentence = "apple banana apple orange banana apple"counts = {}for word in sentence.split(): counts[word] = counts.get(word, 0) + 1print(counts)# {'apple': 3, 'banana': 2, 'orange': 1}
📄 实战 2:嵌套字典初始化
students = {}students.setdefault("john", {})["math"] = 90students.setdefault("john", {})["science"] = 85print(students)# {'john': {'math': 90, 'science': 85}}
📌 方法速查表
方法 | 作用 |
---|---|
get() | 安全取值,可给默认值 |
update() | 合并或批量更新 |
pop() | 删除并返回值 |
popitem() | 删除并返回最近插入的键值对 |
clear() | 清空字典 |
setdefault() | 取不到就设默认值 |
keys() | 返回所有键的视图 |
values() | 返回所有值的视图 |
items() | 返回所有键值对的视图 |
🧠 今日复盘
- 用
get()
优雅地防 KeyError
用 update()
一行合并字典用 pop()
/ popitem()
精准删除用 setdefault()
轻松初始化嵌套结构用 keys()/values()/items()
高效遍历恭喜你,距离 100 Days of Python 毕业又近了一天!明天见~
最后感谢阅读!欢迎关注我,微信公众号:
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!!!