Student grade tracking system with data visualization

Python 字典 (Dictionary) (09):更靈活的應用技巧

在前一篇文章中,我們已經學習了字典的基本操作,包括新增、刪除、修改與查詢。這些功能讓我們能夠快速上手並使用字典處理資料。


然而,Python 的字典還有許多進階用法,例如字典推導式、鍵與值的提取方法、同時遍歷鍵值對,以及如何使用嵌套字典來表示更複雜的資料結構。

這些技巧不僅能提升開發效率,還能幫助你在面對真實專案時,寫出更乾淨且更容易維護的程式碼。

字典推導式

字典推導式(Dict Comprehension)是一種簡潔創建字典的方式,特別適合當你有兩個相關的列表需要組合成字典時。

names = ['小明', '小花', '小華', '小美']
heights = [170, 165, 180, 160]

# 使用字典推導式創建字典
students = {key: value for key, value in zip(names, heights)}
# 結果: {'小明': 170, '小花': 165, '小華': 180, '小美': 160}
  

這種語法簡潔且富有表現力,是 Python 編程中的一大特色。

獲取字典的所有鍵

在處理字典時,我們經常需要獲取所有的鍵。Python 提供了幾種方法:

使用 keys() 方法

test_scores = {"小明": [80, 72, 90], 
              "小花": [88, 68, 81]}
keys = test_scores.keys()
# 返回 dict_keys(['小明', '小花'])
      

keys() 返回一個 dict_keys 對象,這是一個動態視圖,反映字典的當前狀態。

使用 list() 函數

keys_list = list(test_scores)
# 返回 ['小明', '小花']
      

使用 list() 函數可以將鍵轉換為列表,便於進一步處理。

遍歷字典的鍵

for student in test_scores.keys():
    print(student)
# 輸出:
# 小明
# 小花
  

dict_keys 對象可以直接用於迭代,無需轉換為列表。

獲取字典的所有值

與獲取鍵類似,我們也可以獲取字典中的所有值:

使用 values() 方法

test_scores = {"小明": [80, 72, 90], "小花": [88, 68, 81]}
values = test_scores.values()
# 返回 dict_values([[80, 72, 90], [88, 68, 81]])
  

遍歷字典的值

for score_list in test_scores.values():
    print(score_list)
# 輸出:
# [80, 72, 90]
# [88, 68, 81]
  

注意: values() 返回的是一個 dict_values 對象,這是一個動態視圖,可以直接用於迭代,但不能像列表那樣進行索引或切片操作。

如果需要將值轉換為列表,可以使用:

values_list = list(test_scores.values())

同時獲取鍵和值

Python code showing items() method with key-value pairs highlighted

使用 items() 方法可以同時獲取字典的鍵和值:

biggest_brands = {
    "蘋果": 184, 
    "谷歌": 141.7, 
    "微軟": 80
}

for company, value in biggest_brands.items():
    print(company + " 的價值為 " + str(value) + " 十億美元。")
  

輸出:

蘋果 的價值為 184 十億美元。
谷歌 的價值為 141.7 十億美元。
微軟 的價值為 80 十億美元。
  

items() 方法返回一個 dict_items 對象,其中每個元素是一個 (key, value) 形式的元組。

這種方法特別適合需要同時處理鍵和值的情況,使代碼更加簡潔。

字典的嵌套

字典可以包含其他字典作為值,創建多層次的數據結構,適合表示更複雜的關係。

# 學生信息系統
students = {
    "小明": {
        "年齡": 17,
        "成績": {"數學": 95, "語文": 88, "英語": 90},
        "聯絡方式": {"電話": "0912345678", "郵箱": "xiaoming@example.com"}
    },
    "小花": {
        "年齡": 16,
        "成績": {"數學": 92, "語文": 96, "英語": 85},
        "聯絡方式": {"電話": "0923456789", "郵箱": "xiaohua@example.com"}
    }
}
  

訪問嵌套字典

# 獲取小明的數學成績
math_score = students["小明"]["成績"]["數學"]  # 返回 95

# 使用 get() 方法安全訪問
english_score = students.get("小華", {}).get("成績", {}).get("英語", "無記錄")
# 如果小華不存在,返回 "無記錄"
  

嵌套字典特別適合表示具有多層次結構的數據,如組織結構、產品目錄等。

實用的字典方法總結

添加/更新

dict[key] = value – 添加或更新單個鍵值對

dict.update(other_dict) – 添加或更新多個鍵值對

查詢

dict[key] – 使用鍵訪問值(鍵不存在時會出錯)

dict.get(key, default) – 安全地獲取值,可提供默認值

key in dict – 檢查鍵是否存在

刪除

dict.pop(key, default) – 刪除鍵並返回值

del dict[key] – 刪除鍵值對

dict.clear() – 清空字典

迭代

dict.keys() – 獲取所有鍵

dict.values() – 獲取所有值

dict.items() – 獲取所有鍵值對

總結

字典是 Python 中最強大、最常用的資料結構之一,靈活掌握它的進階技巧,將能幫助你在日常開發與專案中,更高效地處理各類資料。

Student grade tracking system with data visualization

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

High Quality

Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor.

Fast Delivery

Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor.

Best Warranty

Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor.