如何在 Python 中建立字典(文字和建構函式)
了解如何在 Python 中建立字典。了解文字語法、字典建構函式、字典推導式和鍵值初始值設定項。
概述
字典是 Python 中最強大且使用最頻繁的內建資料類型之一。字典是一個可變的、有序的(自Python 3.7 起)鍵值對集合,其中每個鍵必須是唯一且可散列的(例如,字串、數字或元組)。字典可讓您以高度最佳化的 O(1) 平均情況時間複雜度執行查找操作。
建立字典最常見、最直接的方法是使用大括號「{}」以及用冒號分隔的鍵值對。例如, `my_dict = {"name": "Alice", "age": 30}` 建立一個填滿字典。要建立空字典,可以使用空花括號“{}”或“dict()”建構函式。
Python 也提供其他進階方法來動態建立字典。 `dict()` 建構子可以從鍵值元組或關鍵字參數清單建立字典。此外,字典推導式提供了一種從現有可迭代物件初始化字典的強大方法,將轉換應用於內聯的鍵或值。
程式碼和執行輸出
這個腳本示範了在 Python 中初始化和建立字典的多種方法。
create_dict.py
在編輯器中嘗試# 1. Dictionary literal syntax (most common)
user = {"name": "Alice", "age": 28, "verified": True}
print("Literal dict:", user)
# 2. Using the dict() constructor with keyword arguments
config = dict(host="localhost", port=8080, debug=True)
print("Constructor dict:", config)
# 3. Creating dictionary from key-value pairs (tuples)
pairs = [("id", 101), ("status", "active")]
status_dict = dict(pairs)
print("From tuples:", status_dict)
# 4. Dictionary comprehension (dynamic creation)
squares = {x: x**2 for x in range(1, 5)}
print("Comprehension:", squares)端子輸出
Literal dict: {'name': 'Alice', 'age': 28, 'verified': True}
Constructor dict: {'host': 'localhost', 'port': 8080, 'debug': True}
From tuples: {'id': 101, 'status': 'active'}
Comprehension: {1: 1, 2: 4, 3: 9, 4: 16}逐步實施
- 使用大括號 {} 和鍵:值對來建立字典文字。
- 呼叫 dict() 建立一個空字典或使用關鍵字參數建構一個字典。
- 將鍵值元組列表傳遞給 dict() 以將關係數組轉換為字典物件。
常見問題解答
列表或字典項可以當字典鍵嗎?
不,字典鍵必須是可散列的(不可變的)。由於列表和字典是可變的,因此它們不能是鍵。元組、字串和整數是有效的鍵。
如何建立具有一組鍵的預設值的字典?
您可以使用 dict.fromkeys(keys_list, default_value) 建構一個字典,其中所有鍵共享相同的預設值。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。