← 從零開始學 Python
第 41 課,共 78 課 · 10 XP
字典
理論與題目說明
機器翻譯,尚未經母語人士審閱。
字典(dict)存放鍵 → 值的配對。用鍵可以馬上找到值:
phone = {"Anna": "+886000000001", "Ben": "+886000000002"}
phone["Anna"] # '+886000000001'
phone["Clara"] = "+886…" # 新增或替換
del phone["Ben"] # 刪除
"Anna" in phone # True —— 檢查鍵
鍵不存在時,phone["David"] 會引發 KeyError。安全的做法是用 get 並給一個預設值:
phone.get("David", "沒有號碼")
迴圈:
for name in phone: # 鍵
...
for name, number in phone.items(): # 配對
print(name, number)
典型的題目是計數:每個詞出現了幾次。
counts = {}
for w in ["a", "b", "a"]:
counts[w] = counts.get(w, 0) + 1
# {'a': 2, 'b': 1}
題目。 寫一個函式 count_words(text),回傳「詞 → 出現次數」的字典。詞用空白分隔,不分大小寫:"Table table" → {'table': 2}。