# 怎么用 Jupyter 學習 Python 字典
## 前言
Python 字典(Dictionary)是 Python 中最重要且常用的數據結構之一。它以鍵值對(key-value)的形式存儲數據,提供了高效的數據查找和管理方式。本文將介紹如何在 Jupyter Notebook 中學習和使用 Python 字典,涵蓋基礎操作、常用方法以及實際應用場景。
---
## 1. 為什么選擇 Jupyter 學習 Python 字典?
Jupyter Notebook 是一個交互式的開發環境,特別適合學習和實驗 Python 代碼。它的優勢包括:
- **即時反饋**:可以逐行執行代碼并查看結果。
- **可視化**:支持 Markdown 注釋和圖表展示。
- **可重復性**:方便保存和分享代碼片段。
---
## 2. Python 字典基礎
### 2.1 字典的定義
字典用花括號 `{}` 定義,鍵值對之間用逗號分隔,鍵和值之間用冒號 `:` 分隔。
```python
# 創建一個空字典
empty_dict = {}
# 創建一個包含鍵值對的字典
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Physics"]
}
通過鍵名訪問對應的值:
print(student["name"]) # 輸出: Alice
如果鍵不存在,會拋出 KeyError??梢允褂?get() 方法避免錯誤:
print(student.get("address", "Not Found")) # 輸出: Not Found
可以通過鍵名直接修改或添加新的鍵值對:
student["age"] = 21 # 修改值
student["address"] = "123 Main St" # 添加新鍵值對
for key in student:
print(key)
for value in student.values():
print(value)
for key, value in student.items():
print(f"{key}: {value}")
類似于列表推導式,可以快速生成字典:
squares = {x: x**2 for x in range(1, 6)}
print(squares) # 輸出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
使用 update() 方法或 ** 操作符:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
# 方法1
dict1.update(dict2)
# 方法2
merged_dict = {**dict1, **dict2}
| 方法 | 描述 | 示例 |
|---|---|---|
keys() |
返回所有鍵 | student.keys() |
values() |
返回所有值 | student.values() |
items() |
返回所有鍵值對 | student.items() |
pop() |
刪除指定鍵并返回值 | student.pop("age") |
clear() |
清空字典 | student.clear() |
copy() |
返回字典的淺拷貝 | new_dict = student.copy() |
用字典統計一段文本中單詞的出現次數:
text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # 輸出: {'apple': 3, 'banana': 2, 'orange': 1}
將學生按成績分組:
students = [
{"name": "Alice", "grade": "A"},
{"name": "Bob", "grade": "B"},
{"name": "Charlie", "grade": "A"}
]
grade_groups = {}
for student in students:
grade = student["grade"]
if grade not in grade_groups:
grade_groups[grade] = []
grade_groups[grade].append(student["name"])
print(grade_groups) # 輸出: {'A': ['Alice', 'Charlie'], 'B': ['Bob']}
使用 in 關鍵字:
if "name" in student:
print("Key exists")
字典本身是無序的,但可以通過 sorted() 函數對鍵或值排序:
sorted_keys = sorted(student.keys())
sorted_values = sorted(student.values())
Python 字典是一種靈活且強大的數據結構,適用于各種場景。通過 Jupyter Notebook 的交互式環境,可以高效學習和實驗字典的操作。本文介紹了字典的基礎語法、常用方法和實際應用,希望能幫助你掌握這一重要工具。
在 Jupyter 中完成這些練習,加深對字典的理解! “`
這篇文章共計約1950字,涵蓋了 Python 字典的基礎知識、常用操作、實際應用以及練習題目,適合在 Jupyter Notebook 中邊學邊練。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。