EADST

Python 字典dict删除元素

# ============================================
# Python 字典(dict)删除元素(4种常用方法)
# 作者:XD
# 日期:2025-10-11
# ============================================

# 在 Python 中,字典(dict)是一种键值对(key-value)数据结构。
# 在实际编程中,我们经常需要删除字典中的某些元素。
# 下面介绍 4 种常用的删除方法:
# 1. 使用 del 关键字按键删除
# 2. 使用 pop() 方法按键删除并返回值
# 3. 使用 popitem() 删除最后一对键值
# 4. 使用 clear() 清空整个字典


# ------------------------------------------------
# 1. del:按键删除元素
# ------------------------------------------------
# del 是 Python 的关键字,用于删除变量、列表元素或字典中的键值对。
# 语法:
# del dictname[key]
# 如果 key 不存在,会抛出 KeyError。

person = {"name": "Alice", "age": 25, "city": "Beijing"}
print(person)

# 删除指定键 'age'
del person["age"]
print(person)

# 删除不存在的键会报错
# del person["gender"]  # KeyError: 'gender'

# 可以先判断键是否存在再删除
if "gender" in person:
    del person["gender"]
else:
    print("键 'gender' 不存在,无法删除。")


# ------------------------------------------------
# 2. pop():按键删除并返回被删除的值
# ------------------------------------------------
# 语法:
# dictname.pop(key[, default])
# 如果指定的 key 存在,则删除并返回对应的 value;
# 如果 key 不存在且未提供 default 参数,则抛出 KeyError。

student = {"id": 101, "name": "Tom", "score": 89}

# 删除键 'score' 并返回它的值
removed = student.pop("score")
print(f"删除的值为:{removed}")
print(student)

# 删除不存在的键并提供默认值(不会报错)
removed = student.pop("grade", "无此项")
print(f"删除结果:{removed}")
print(student)


# ------------------------------------------------
# 3. popitem():删除最后一个键值对
# ------------------------------------------------
# 语法:
# dictname.popitem()
# popitem() 会删除并返回字典中的最后一项(键值对),返回结果是一个元组 (key, value)
# 在 Python 3.7+ 中,字典是有序的,因此 popitem() 删除的是最后插入的那一项。

info = {"a": 1, "b": 2, "c": 3}
print("删除前:", info)

# 删除最后一个键值对
item = info.popitem()
print(f"删除的键值对:{item}")
print("删除后:", info)

# 连续调用 popitem() 直到字典为空
while info:
    print("继续删除:", info.popitem())
print("最终字典为空:", info)


# ------------------------------------------------
# 4. clear():清空整个字典
# ------------------------------------------------
# 语法:
# dictname.clear()
# 清空所有键值对,相当于将字典重置为空。

config = {"host": "localhost", "port": 8080, "debug": True}
print("原字典:", config)

config.clear()
print("清空后:", config)  # 输出:{}


# ------------------------------------------------
# ✅ 四种方法对比总结:
# ------------------------------------------------
# | 方法         | 删除依据 | 是否返回值 | 可删除范围 | 错误情况 |
# |---------------|-----------|-------------|-------------|-----------|
# | del           | 键       | 无          | 指定键     | 键不存在时报错 |
# | pop()         | 键       | 有(返回值) | 指定键     | 键不存在时报错,可指定默认值 |
# | popitem()     | 无(删除最后一项) | 有(返回元组) | 最后一项 | 空字典时报错 |
# | clear()       | 无       | 无          | 所有键值对 | 无 |

# ------------------------------------------------
# 使用建议:
# - 想删除并获取被删值 → 用 pop()
# - 想删除最后一个元素 → 用 popitem()
# - 删除特定键且不需返回 → 用 del
# - 清空整个字典 → 用 clear()
# ------------------------------------------------
相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
Diagram PyCharm Algorithm Quantize Distillation FP16 继承 Math uwsgi Hilton Hotel diffusers FastAPI IndexTTS2 Github Website 云服务器 QWEN llama.cpp CUDA Magnet Plate 搞笑 Shortcut Ptyhon 强化学习 tar COCO Video SQLite News CC 财报 Template 证件照 域名 NLTK Google Python Rebuttal MD5 Dataset Sklearn Vmess v2ray FlashAttention 论文速读 TensorRT Llama SQL 多进程 Attention Claude Jev Streamlit Card TSV Vim Docker 关于博主 Heatmap 签证 v0.dev LLAMA CEIR CAM Statistics FP64 FP8 LeetCode 版权 Breakpoint Web Disk Pillow Firewall 图标 Paddle C++ SPIE 图形思考法 WAN Conda HaggingFace NameSilo scipy OpenAI YOLO Search PDF 飞书 CV Numpy BTC FP32 Safetensors SAM CLAP Gemma transformers Freesound Knowledge Pickle Qwen2 第一性原理 API ModelScope Git 报税 Proxy Jupyter UI Bert Pandas Excel Django Pytorch CSV Logo 顶会 算法题 自我改进 git-lfs logger Permission Bin DeepStream Paper WebCrawler VPN Land NLP BF16 音频 ONNX ChatGPT RAR Qwen Linux hf DeepSeek Ubuntu UNIX GIT Zip Clash GPTQ Plotly git Review LaTeX JSON XGBoost Hungarian Tensor TensorFlow API网关 printf icon Color Password 递归学习法 Transformers LoRA BeautifulSoup Translation Cloudreve VSCode Qwen2.5 公式 OCR Bitcoin Animate 腾讯云 Data tqdm ms-swift ResNet-50 Input VGG-16 Image2Text Random AI Food Michelin 净利润 Windows CTC XML TTS Tracking InvalidArgumentError Quantization Use PIP torchinfo PyTorch Jetson uWSGI 多线程 长期记忆 阿里云 Nginx SVR Interview EXCEL Harness Domain Baidu Crawler HuggingFace LLM 论文 Augmentation OpenCV PDB GGML Miniforge Datetime Base64 Mixtral Bipartite Anaconda 个人博客 Markdown GPT4 Tiktoken RL GoogLeNet mmap Agent RGB
站点统计

本站现有博文340篇,共被浏览1017346次

本站已经建立2718天!

热门文章
文章归档
回到顶部