苦练Python第26天:精通字典8大必杀技

苦练Python第26天:精通字典8大必杀技

前言

大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

现在我们已经把字典的基本概念摸得门儿清,今天继续升级,把字典的"隐藏技能"一次点满,让你成为真正的 字典忍者!🥷🐍


📦 今日收获清单

  • 掌握 get()update()pop() 等高频方法
  • 学会安全取值、合并字典、优雅删改
  • 配合真实场景,即学即用

🧠 字典热身回顾

字典的本质就是 键值对

  • 键必须唯一且不可变(字符串、数字、元组等)
  • 值想放啥就放啥
python 复制代码
user = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}

🔍 1. get(key[, default]) ------ 安全取值不翻车

python 复制代码
print(user.get("age"))            # 30
print(user.get("email"))          # None
print(user.get("email", "N/A"))   # N/A

✅ 当键不存在时,直接返回 None 或你指定的默认值,程序再也不会因为 KeyError 崩溃。


➕ 2. update(other_dict) ------ 一键合并/覆盖

python 复制代码
user.update({"email": "alice@example.com"})
print(user)
# {'name': 'Alice', 'age': 30, 'city': 'Paris', 'email': 'alice@example.com'}

✅ 同名键会被覆盖,想更新年龄也就一行:

python 复制代码
user.update({"age": 31})  # age 从 30 变 31

❌ 3. pop(key[, default]) ------ 删除并返回值

python 复制代码
age = user.pop("age")
print(age)   # 31
print(user)  # 字典里已没有 'age'

如果键不存在,又不想抛错:

python 复制代码
email = user.pop("email", "not found")

🚫 4. popitem() ------ 弹出"最新"键值对(Python 3.7+)

python 复制代码
last = user.popitem()
print(last)   # ('email', 'alice@example.com')

✅ 把字典当栈用,先进后出。


🧽 5. clear() ------ 一键清空

python 复制代码
user.clear()
print(user)  # {}

🆕 6. setdefault(key[, default]) ------ 取不到就创建

python 复制代码
settings = {"theme": "dark"}

theme = settings.setdefault("theme", "light")     # 已存在,返回 'dark'
lang  = settings.setdefault("language", "English")# 不存在,新增并返回 'English'

print(settings)
# {'theme': 'dark', 'language': 'English'}

✅ 初始化嵌套结构时特别香:

python 复制代码
students = {}
students.setdefault("john", {})["math"] = 90
students.setdefault("john", {})["science"] = 85
print(students)
# {'john': {'math': 90, 'science': 85}}

📋 7. keys() · values() · items() ------ 遍历三剑客

python 复制代码
print(user.keys())    # dict_keys(['name', 'city'])
print(user.values())  # dict_values(['Alice', 'Paris'])
print(user.items())   # dict_items([('name', 'Alice'), ('city', 'Paris')])

循环用法:

python 复制代码
for key, value in user.items():
    print(f"{key} = {value}")

🔎 8. in 关键字 ------ 快速判断键是否存在

python 复制代码
if "name" in user:
    print("User has a name")

⚠️ 只扫键,不扫值。


🧪 实战 1:单词计数器

python 复制代码
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:嵌套字典初始化

python 复制代码
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() 高效遍历

恭喜你,距离 100 Days of Python 毕业又近了一天!明天见~

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!

相关推荐
GISer_Jing5 小时前
AI自动化工作流:智能驱动未来(升级研究生项目!!!)
人工智能·前端框架·自动化
草捏子5 小时前
Agent Skills:让 AI 一次学会、永远记住的能力扩展方案
人工智能
NocoBase6 小时前
【2.0 教程】第 1 章:认识 NocoBase ,5 分钟跑起来
数据库·人工智能·开源·github·无代码
后端小肥肠6 小时前
OpenClaw实战|从识图到公众号内容自动化,我跑通了完整链路
人工智能·aigc·agent
猿界零零七6 小时前
pip install mxnet 报错解决方案
python·pip·mxnet
Elastic 中国社区官方博客6 小时前
快速 vs. 准确:衡量量化向量搜索的召回率
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索
qq_381338506 小时前
【技术日报】2026-03-18 AI 领域重磅速递
大数据·人工智能
NocoBase6 小时前
开源项目管理工具选型指南(2026年最新)
人工智能·开源·无代码
feasibility.6 小时前
AI 爬虫高手养成:Openclaw+Scrapling 手动部署 + 采集策略(以Walmart 电商平台为例)
人工智能·爬虫·科技·机器人·agi·openclaw·scrapling
程序员老猫6 小时前
前端菜鸡狂喜!DeepSeek+Gemini,嘴炮出完整博客方案
人工智能