Python字典(Dictionary)入門:概念和基本使用
1. 字典的基本概念
字典特點:
- 使用鍵值對(key-value pairs)儲存數據
- 鍵(key)必須是唯一的
- 鍵必須是不可變類型(字符串、數字、元組)
- 值(value)可以是任何類型
- 字典是可變的(mutable)
# 創建字典
empty_dict = {}
empty_dict2 = dict()
# 基本字典
student = {
"name": "張三",
"age": 20,
"score": 85
}
# 使用dict()函數創建
info = dict(name="李四", age=22, city="台北")
# 混合數據類型
mixed = {
1: "整數鍵",
"list": [1, 2, 3],
"tuple": (4, 5, 6),
"dict": {"a": 1, "b": 2}
}
2. 訪問和修改字典
# 訪問值
student = {"name": "張三", "age": 20, "score": 85}
print(student["name"]) # 張三
print(student.get("age")) # 20
print(student.get("phone", "未設置")) # 使用默認值
# 修改值
student["age"] = 21
student["phone"] = "123456789" # 添加新鍵值對
student.update({"email": "zhang@example.com", "age": 22})
# 刪除鍵值對
del student["phone"]
email = student.pop("email")
last_item = student.popitem() # 刪除並返回最後一個鍵值對
3. 實際應用範例
學生成績管理系統
class_scores = {
"張三": {"數學": 85, "英語": 92, "物理": 78},
"李四": {"數學": 92, "英語": 85, "物理": 90},
"王五": {"數學": 78, "英語": 85, "物理": 95}
}
# 計算每個學生的平均分
for student, scores in class_scores.items():
average = sum(scores.values()) / len(scores)
print(f"{student}的平均分是:{average:.1f}")
購物車系統
shopping_cart = {}
def add_item(item, price, quantity=1):
if item in shopping_cart:
shopping_cart[item]["quantity"] += quantity
else:
shopping_cart[item] = {"price": price, "quantity": quantity}
def calculate_total():
return sum(item["price"] * item["quantity"] for item in shopping_cart.values())
add_item("蘋果", 30, 2)
add_item("香蕉", 25, 3)
add_item("蘋果", 30, 1) # 增加已有商品的數量
print(f"購物車總金額:{calculate_total()}元")
4. 字典進階操作
# 字典推導式
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 合併字典
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2} # Python 3.5+
# 遍歷字典
student = {"name": "張三", "age": 20, "score": 85}
for key in student.keys():
print(key)
for value in student.values():
print(value)
for key, value in student.items():
print(f"{key}: {value}")
5. 練習題
-
實現通訊錄系統:
- 添加聯繫人(姓名、電話、郵箱)
- 修改聯繫人信息
- 刪除聯繫人
- 搜索聯繫人
- 顯示所有聯繫人
-
商品庫存管理:
- 記錄商品信息(名稱、價格、庫存量)
- 更新庫存
- 計算庫存總值
- 顯示庫存不足的商品
- 生成庫存報表