返回博客

13. dict 与 set:字典与集合

13. dict 与 set:字典与集合

第十三篇:dict 与 set——字典与集合完全指南

前言

**字典(dict)和集合(set)**是 Python 中两种强大的关联数据结构。字典通过键值对实现 O(1) 的查找效率,集合用于高效去重和数学集合运算。

字典(dict)基础

创建方式

empty = {}
student = {"name": "小明", "age": 25, "score": 92}
pairs = [("name", "小明"), ("age", 25)]
from_pairs = dict(pairs)
user = dict(name="小红", age=22, city="北京")

len() 函数

user = {"name": "小明", "age": 25, "city": "北京"}
print(len(user))  # 3

dict 的基本操作

索引访问与安全获取

student = {"name": "小明", "age": 25}
# print(student["grade"])  # KeyError!
print(student.get("name"))       # 小明
print(student.get("grade", "N/A"))  # N/A

添加、修改与删除

student = {"name": "小明", "age": 25}
student["grade"] = "三年级"
student.update({"score": 95})
age = student.pop("age")  # 25
missing = student.pop("grade", "未知")
del student["name"]
student.clear()

常用方法

for key in student.keys():    pass
for value in student.values(): pass
for key, value in student.items(): pass
result = student.setdefault("key", "value")
copy_student = student.copy()

字典推导式

squares = {x: x ** 2 for x in range(1, 6)}
evens = {x: x ** 2 for x in range(1, 11) if x % 2 == 0}
upper_names = {k.upper(): v for k, v in student.items()}
matrix = {(i, j): i * j for i in range(1, 4) for j in range(1, 4)}

集合(set)基础

创建方式

empty = set()  # ⚠️ {} 是空字典
colors = {"red", "green", "blue"}
duplicates = [1, 2, 2, 3]
unique = set(duplicates)  # {1, 2, 3}

集合的基本操作

colors.add("yellow")
colors.update(["white", "black"])
colors.remove("red")   # KeyError if missing
colors.discard("orange")  # Safe removal
removed = colors.pop()
colors.clear()

集合的数学运算

操作 运算符 方法
交集 & .intersection()
并集 | .union()
差集 - .difference()
对称差 ^ .symmetric_difference()
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
print(a & b)         # {4, 5}
print(a | b)         # {1-8}
print(a - b)         # {1, 2, 3}
print(a ^ b)         # {1, 2, 3, 6, 7, 8}

子集/超集检查

base = {1, 2, 3, 4, 5}
subset = {1, 2, 3}
print(subset.issubset(base))  # True
print(base > subset)          # True — 真超集
print(a.isdisjoint(b))        # 无共同元素检查

集合推导式

squares = {x ** 2 for x in range(1, 6)}  # {1, 4, 9, 16, 25}
vowels = {char for word in ["apple", "banana"] for char in word if char in {"a", "e", "i", "o", "u"}}

frozenset 不可变集合

fs = frozenset([1, 2, 3])
data = {frozenset(["a", "b"]): 1}  # 可作为字典键

实战示例

词频统计

def count_words(text):
    words = text.lower().split()
    counter = {}
    for word in words:
        clean = word.strip(".,!?;:'()-")
        if clean:
            counter[clean] = counter.get(clean, 0) + 1
    return counter

defaultdict 简化代码

from collections import defaultdict
groups = defaultdict(list)
for item in ["apple", "apricot", "banana"]:
    groups[item[0]].append(item)
print(dict(groups))  # {'a': ['apple', 'apricot'], 'b': ['banana']}

性能特点

  • dict/set 底层基于哈希表 — 查找 O(1)
  • list 查找 O(n) — 随规模线性增长
  • 可哈希约束 — 可变类型不能作为 dict 键或 set 元素

总结

  1. dict 创建 — 字面量/dict() 构造函数
  2. 增删改查 — update/pop/del/get/setdefault/clear
  3. 遍历方法 — keys()/values()/items()
  4. 成员检查 — in/not in 只检查键
  5. 字典推导式 — 简洁高效的创建方式
  6. set 创建 — 注意 set() ≠ {}
  7. add/remove/discard/pop/clear
  8. frozenset — 不可变集合
  9. 数学运算 — 交并差集、子集超集、不相交检查
  10. 性能 — 哈希表 O(1) 查找 vs list O(n)
  11. 实用技巧 — defaultdict、嵌套字典

下一篇文章将深入讲解类与实例:面向对象编程基础。


本文是 Python 教程系列的第十三篇。