Python 使用 Dict 和 Set:從入門到進階
Python 里的 dict(字典)和 set(集合)是非常常用的數據結構。它們不僅高效,而且語法也不復雜,是你寫出優雅 Python 代碼的必經之路。
它們是 Python 的王牌數據結構之一,掌握它們,你的代碼會更簡潔更高效。
參考文章: Python 使用 Dict 和 Set | 簡單一點學習
一、基礎入門:搞懂 dict 和 set 是啥
1.1 什么是 dict(字典)?
字典是“鍵-值”對的集合,鍵是唯一的,值可以是任意對象。
person = {
"name": "小明",
"age": 18,
"city": "北京"
}
字典的特點:
- 鍵必須是不可變類型(通常是字符串、數字、元組)
- 查找速度快,效率高
- 無序(從 Python 3.7 開始,插入順序會被保留)
1.2 什么是 set(集合)?
集合是一個無序、無重復元素的集合體。
fruits = {"apple", "banana", "orange"}
集合的特點:
- 元素唯一,自動去重
- 可用于集合運算(交集、并集、差集等)
- 也是無序的,不能通過索引訪問
二、常見操作:增刪改查那點事
2.1 字典 dict 的基本操作
person = {"name": "小明", "age": 18}
# 查
print(person["name"]) # 小明
print(person.get("gender")) # None,不會報錯
# 增
person["gender"] = "male"
# 改
person["age"] = 20
# 刪
del person["gender"]
person.pop("age") # 返回值是被刪掉的值
# 遍歷
for key, value in person.items():
print(key, value)
2.2 集合 set 的基本操作
fruits = {"apple", "banana"}
# 查(不能用索引,只能遍歷)
for fruit in fruits:
print(fruit)
# 增
fruits.add("orange")
# 刪
fruits.remove("banana") # 如果沒有這個元素會報錯
fruits.discard("peach") # 不報錯
# 清空
fruits.clear()
三、進階用法:操作集合和字典的騷技巧
3.1 字典推導式
快速構建字典的方式:
squares = {x: x * x for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
3.2 集合推導式
unique_even = {x for x in range(10) if x % 2 == 0}
# {0, 2, 4, 6, 8}
3.3 字典常用方法
person.keys() # 所有鍵
person.values() # 所有值
person.items() # 所有鍵值對
person.update({"job": "engineer"}) # 批量更新
3.4 集合運算
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # 并集 {1, 2, 3, 4}
print(a & b) # 交集 {2, 3}
print(a - b) # 差集 {1}
print(a ^ b) # 對稱差集 {1, 4}
四、高級進階:騷操作和性能優化
4.1 用 set 做去重
nums = [1, 2, 2, 3, 4, 4]
unique = list(set(nums)) # 去重后轉回列表
4.2 用 dict 做計數器(不推薦手寫,推薦用 Counter)
words = ["apple", "banana", "apple"]
counter = {}
for word in words:
counter[word] = counter.get(word, 0) + 1
或者用標準庫里的:
from collections import Counter
counter = Counter(words)
4.3 用 dict 模擬 switch-case 語句
def add(): print("加法")
def sub(): print("減法")
func_map = {
"add": add,
"sub": sub
}
func_map.get("add", lambda: print("無操作"))()
4.4 用 frozenset 當字典鍵
因為普通 set 不可哈希,不能作為字典鍵,但 frozenset 可以:
d = {}
key = frozenset([1, 2, 3])
d[key] = "這是一個鍵"
五、總結一下
| 對象 | 特性 | 主要應用場景 |
|---|---|---|
| dict | 鍵值對存儲,查找快 | 結構化數據,映射、緩存 |
| set | 無重復元素,集合運算 | 去重、成員判斷、數學集合 |

浙公網安備 33010602011771號