苦练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 毕业又近了一天!明天见~

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

相关推荐
Kaydeon37 分钟前
【Anaconda】Conda 虚拟环境打包迁移教程
人工智能·pytorch·python·conda
love530love38 分钟前
《Anaconda 精简路径治理》系列 · 番外篇Conda 虚拟环境路径结构方案全解——六种路径布局对比、优劣与治理建议
运维·人工智能·windows·python·conda
F_D_Z4 小时前
【PyTorch】图像二分类项目
人工智能·pytorch·深度学习·分类·数据挖掘
Yweir4 小时前
Elastic Search 8.x 分片和常见性能优化
java·python·elasticsearch
小蜗牛狂飙记5 小时前
在github上传python项目,然后在另外一台电脑下载下来后如何保障成功运行
开发语言·python·github
心平愈三千疾5 小时前
学习秒杀系统-页面优化技术
java·学习·面试
倔强青铜三5 小时前
苦练Python第27天:嵌套数据结构
人工智能·python·面试
martian6656 小时前
深入详解随机森林在眼科影像分析中的应用及实现细节
人工智能·算法·随机森林·机器学习·医学影像
望百川归海6 小时前
基于自定义数据集微调SigLIP2-分类任务
人工智能·分类·数据挖掘