Python 字典 (dict) 型別詳解:建立、操作、方法與應用

Python 字典 (dict) 型別詳解:建立、操作、方法與應用 - CCC Blog
一本攤開的字典或索引簿,象徵著 Python 字典的鍵值對 (key-value) 結構。

在 Python 程式設計中,字典 (dict) 是一種非常有用且靈活的資料結構,用於儲存鍵值對 (key-value pair)。本文將詳細介紹 Python 字典的定義、建立方式、特性、基本操作、常用方法、迭代,以及實際應用。

什麼是字典 (dict)?

字典是一種可變的、以鍵值對 (key-value pair) 形式儲存資料的資料結構。字典具有以下特點:

  • 鍵值對 (Key-Value Pair): 字典中的每個元素都由一個鍵 (key) 和一個值 (value) 組成,鍵和值之間用冒號 (:) 分隔。
  • 可變性 (Mutable): 字典的內容可以修改 (新增、刪除、修改鍵值對)。
  • 鍵的唯一性 (Unique Keys): 字典中的鍵必須是唯一的,不能重複。如果插入重複的鍵,後面的值會覆蓋前面的值。
  • 鍵的不可變性 (Immutable Keys): 字典的鍵必須是不可變的資料型別 (例如整數、字串、元組),不能是可變的資料型別 (例如串列)。值則可以是任意的資料型別。

關於順序性: 在 Python 3.7 及以後的版本中,字典會保留元素的插入順序。但在之前的版本中,字典是無序的。為確保程式碼的相容性與可讀性,我們通常仍將字典視為「無序」的集合,不應依賴其順序來編寫程式碼。

建立字典

有幾種方式可以建立字典:

  • 使用大括號 {} (最常見): 將鍵值對用逗號分隔,並放在大括號中。
  • 使用 dict() 函數: 可傳入鍵值對序列或使用關鍵字參數來建立。
# 1. 使用大括號 {}
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
empty_dict = {}

# 2. 使用 dict() 函數
# a. 傳入鍵值對序列
pairs = [('a', 1), ('b', 2), ('c', 3)]
my_dict_from_pairs = dict(pairs)  # 結果: {'a': 1, 'b': 2, 'c': 3}

# b. 使用關鍵字參數
my_dict_from_kwargs = dict(name='Bob', age=25, country='USA') 
# 結果: {'name': 'Bob', 'age': 25, 'country': 'USA'}

print(type(person))  # 輸出: <class 'dict'>

字典的基本操作

字典的核心操作圍繞著它的鍵 (key) 進行。

  • 存取: dict[key]。如果鍵不存在,會引發 KeyError
  • 新增 / 修改: dict[key] = value。 如果鍵已存在,則修改值;如果不存在,則新增鍵值對。
  • 刪除: del dict[key]
  • 檢查鍵是否存在: key in dict
  • 取得長度: len(dict)
student = {'name': 'Charlie', 'grade': 'A', 'age': 12}

# 存取
print(student['name'])   # 輸出: Charlie

# 新增
student['score'] = 95
# student is now {'name': 'Charlie', 'grade': 'A', 'age': 12, 'score': 95}

# 修改
student['age'] = 13
# student is now {'name': 'Charlie', 'grade': 'A', 'age': 13, 'score': 95}

# 刪除
del student['grade']
# student is now {'name': 'Charlie', 'age': 13, 'score': 95}

# 檢查鍵是否存在
print('name' in student)    # 輸出: True
print('gender' in student)  # 輸出: False

# 字典長度
print(len(student)) # 輸出: 3

字典的常用方法

Python 字典提供了許多實用的方法來操作資料。

方法說明
keys()返回包含所有鍵的「視圖 (view)」物件。
values()返回包含所有值的「視圖」物件。
items()返回包含所有 (鍵, 值) 元組的「視圖」物件。
get(key, default)安全地獲取值。如果鍵不存在,返回 default 值 (預設為 None),而不是引發錯誤。
pop(key, default)移除並返回指定鍵的值。如果鍵不存在且未提供 default,則引發錯誤。
popitem()移除並返回最後插入的鍵值對 (Python 3.7+)。
update(other_dict)用另一個字典的鍵值對來更新當前字典。
clear()清空字典中的所有元素。
copy()返回字典的淺拷貝 (shallow copy)。
person = {'name': 'David', 'age': 40, 'city': 'London'}

print(person.keys())      # 輸出: dict_keys(['name', 'age', 'city'])
print(person.values())    # 輸出: dict_values(['David', 40, 'London'])
print(person.items())     # 輸出: dict_items([('name', 'David'), ('age', 40), ('city', 'London')])

# 使用 get() 安全地存取
print(person.get('name'))           # 輸出: David
print(person.get('country'))        # 輸出: None
print(person.get('country', 'N/A')) # 輸出: N/A

# 使用 pop()
age = person.pop('age')
print(f"Popped age: {age}") # 輸出: 40
# person is now {'name': 'David', 'city': 'London'}

# 使用 update()
person2 = {'age': 41, 'gender': 'male'}
person.update(person2)
# person is now {'name': 'David', 'city': 'London', 'age': 41, 'gender': 'male'}
print(person)

字典的迭代 (Iteration)

您可以使用 for 迴圈輕鬆地迭代字典的鍵、值或鍵值對:

person = {'name': 'Eve', 'age': 28, 'country': 'Canada'}

# 迭代鍵 (預設行為)
print("--- Keys ---")
for key in person:
    print(key)

# 迭代值
print("--- Values ---")
for value in person.values():
    print(value)

# 迭代鍵值對
print("--- Items ---")
for key, value in person.items():
    print(f"{key}: {value}")

字典的應用

  • 儲存結構化資料: 例如,表示一個人的資訊 (姓名、年齡、地址等),或一本書的屬性 (書名、作者、ISBN)。
  • 計數: 高效地統計元素出現的次數。
  • 建立對應關係: 表示一對一或一對多的對應關係 (例如,學號對應學生姓名)。
  • 快取 (Caching): 將耗時的計算結果儲存在字典中,當再次需要時直接查詢,避免重複計算。
  • 傳遞函式參數: 函式中的 **kwargs 就是以字典形式傳遞。

總結

Python 的字典 (dict) 是一種功能強大且用途廣泛的資料結構,用於儲存鍵值對。它提供了基於鍵的快速資料存取能力,使其成為組織和管理結構化資料的理想選擇。確實了解字典的特性、操作和常用方法,對於任何 Python 開發者來說都至關重要。

較新的 較舊