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

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

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

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

什麼是字典 (dict)?

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

  • 鍵值對 (Key-Value Pair): 字典中的每個元素都由一個鍵 (key) 和一個值 (value) 組成,鍵和值之間用冒號 (:) 分隔。
  • 無序性 (Unordered): 字典中的元素沒有固定的順序 (不像串列和元組)。在 Python 3.7 及以後的版本中,字典會保留插入順序,但这只是實現細節,不應依賴此特性來編寫程式碼。
  • 可變性 (Mutable): 字典的內容可以修改 (新增、刪除、修改鍵值對)。
  • 鍵的唯一性 (Unique Keys): 字典中的鍵必須是唯一的,不能重複。如果插入重複的鍵,後面的值會覆蓋前面的值。
  • 鍵的不可變性 (Immutable Keys):** 字典的鍵必須是不可變的資料型別 (例如整數、浮點數、字串、元組),不能是可變的資料型別 (例如串列、字典、集合)。 值則可以是任意的資料型別。

在 Python 中,字典屬於 dict 型別。

建立字典

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

  • 使用大括號 {} (最常見): 將鍵值對用逗號分隔,並放在大括號中。
  • 使用 dict() 函數:
    • 不傳入參數,建立空字典。
    • 傳入鍵值對序列 (例如,由元組組成的串列)。
    • 使用關鍵字參數 (keyword arguments)。

# 使用大括號 {}
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
empty_dict = {}

# 使用 dict() 函數
# 1. 不傳入參數
empty_dict2 = dict()

# 2. 傳入鍵值對序列
pairs = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(pairs)  # 輸出: {'a': 1, 'b': 2, 'c': 3}

# 3. 使用關鍵字參數
my_dict2 = dict(name='Bob', age=25, country='USA') #輸出: {'name': 'Bob', 'age': 25, 'country': 'USA'}

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

字典的基本操作

  • 新增/修改: dict[key] = value。 如果Key已經存在,則修改value;如果key不存在,則新增。
  • 刪除: del dict[key]
  • 存取: dict[key]。如果Key不存在,會產生KeyError。
  • 檢查Key是否存在: key in dict
  • 取得長度: len(dict)

# 建立字典
student = {'name': 'Charlie', 'grade': 'A', 'age': 12}

# 存取
print(student['name'])   # 輸出: Charlie
# print(student['score'])  # 引發 KeyError: 'score'

# 新增
student['score'] = 95
print(student)  # 輸出: {'name': 'Charlie', 'grade': 'A', 'age': 12, 'score': 95}

# 修改
student['age'] = 13
print(student)  # 輸出: {'name': 'Charlie', 'grade': 'A', 'age': 13, 'score': 95}

# 刪除
del student['grade']
print(student)  # 輸出: {'name': 'Charlie', 'age': 13, 'score': 95}

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

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

字典的常用方法

  • keys(): 返回包含所有鍵的視圖 (view) 物件。
  • values(): 返回包含所有值的視圖物件。
  • items(): 返回包含所有鍵值對 (以元組形式) 的視圖物件。
  • get(key[, default]): 返回指定鍵的值,如果鍵不存在,返回預設值 (預設為 None)。
  • pop(key[, default]): 移除並返回指定鍵的值,如果鍵不存在,返回預設值 (如果沒有提供預設值,則引發 KeyError)。
  • popitem(): 移除並返回任意一個鍵值對 (Python 3.7+ 保證移除最後插入的鍵值對)。
  • clear(): 清空字典。
  • update(other_dict): 用另一個字典更新當前字典 (如果有相同的鍵,則覆蓋)。
  • copy(): 返回dict的淺拷貝。

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')])

print(person.get('name'))       # 輸出: David
print(person.get('country'))    # 輸出: None
print(person.get('country', 'Unknown'))  # 輸出: Unknown

age = person.pop('age')
print(age)          # 輸出: 40
print(person)       # 輸出: {'name': 'David', 'city': 'London'}

item = person.popitem() # ('city', 'London')
print(person)  # 輸出: {'name': 'David'}

person.clear()
print(person) # {}

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

字典的迭代 (Iteration)

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


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

# 迭代鍵
for key in person:  # 或 for key in person.keys():
    print(key)

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

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

字典的應用

  • 儲存結構化資料: 例如,表示一個人的資訊 (姓名、年齡、地址等)。
  • 計數: 統計元素出現的次數。
  • 對應關係: 表示一對一或一對多的對應關係 (例如,單字和定義、學生和成績)。
  • 快取 (Caching): 將計算結果儲存在字典中,避免重複計算。
  • 資料庫查詢結果: 資料庫查詢結果通常以字典的形式返回。

總結

Python 的字典 (dict) 是一種功能強大且用途廣泛的資料結構,用於儲存鍵值對。了解字典的特性、操作和方法,對於 Python 程式設計非常重要。 字典提供了一種高效的方式來組織和存取資料。

張貼留言

較新的 較舊