HOWTO · Python
Python 中的字典陣列或列表
本教程演示瞭如何在 Python 中建立字典陣列
本頁內容
Python 的 list 通常用來存放一組字典:每個串列元素都能保存一筆由鍵值組成的資料。雖然有時會把這種結構稱為字典陣列,但 Python 串列和專門的陣列型別並不相同。以下範例將說明如何建立串列、存取資料與值、附加一筆資料,以及更新值。
在 Python 中建立字典串列
將每個字典寫成串列常值中的一個元素。每個字典常值都會建立獨立的字典,因此各筆資料可以使用不同的鍵,也可以共用部分鍵。請使用 records 這類描述性變數名稱;list 已是 Python 內建名稱。
執行此範例:
本節中的程式碼以及顯示的標籤或輸出仍為英文。
records = [
{"name": "Ada", "role": "engineer"},
{"name": "Lin", "role": "designer"},
]
print(records)
[{'name': 'Ada', 'role': 'engineer'}, {'name': 'Lin', 'role': 'designer'}]
依索引與鍵存取字典及其值
Python 串列索引從 0 開始,因此索引 1 會選取第二個字典。若要讀取欄位,先依串列索引選取字典,再用方括號中的鍵取得值。這個運算式一次完成串列查找與字典查找兩個步驟。
本節中的程式碼以及顯示的標籤或輸出仍為英文。
records = [
{"name": "Ada", "role": "engineer"},
{"name": "Lin", "role": "designer"},
]
second_record = records[1]
role = records[1]["role"]
print(second_record)
print(role)
{'name': 'Lin', 'role': 'designer'}
designer
若要成功使用方括號查找,所選字典中必須存在該鍵。如果鍵可能不存在,請使用 record.get("role");預設會傳回 None。也可以提供備用值,例如 record.get("role", "unknown")。
將字典附加至串列
呼叫 append(),將一個字典加到現有串列的末尾。這會直接修改原串列,不會建立新串列。
本節中的程式碼以及顯示的標籤或輸出仍為英文。
records = [{"name": "Ada", "role": "engineer"}]
records.append({"name": "Lin", "role": "designer"})
print(records)
[{'name': 'Ada', 'role': 'engineer'}, {'name': 'Lin', 'role': 'designer'}]
更新串列中的字典
先依索引選取一筆資料,再透過鍵指定新值。若指定的鍵原本不存在,指派時就會新增該鍵;因此這種寫法既能取代欄位值,也能新增欄位。
本節中的程式碼以及顯示的標籤或輸出仍為英文。
records = [{"name": "Ada", "role": "engineer"}]
records[0]["role"] = "lead engineer"
records[0]["team"] = "platform"
print(records)
[{'name': 'Ada', 'role': 'lead engineer', 'team': 'platform'}]
使用串列推導式建立字典串列
當每筆資料的格式相同時,串列推導式能讓寫法更精簡。在運算式中放入字典常值,每次迭代就會建立一個不同的字典。例如,下方會建立四個欄位相同、彼此獨立的字典:
本節中的程式碼以及顯示的標籤或輸出仍為英文。
records = [{"active": True, "score": 0} for _ in range(4)]
print(records)
[{'active': True, 'score': 0}, {'active': True, 'score': 0}, {'active': True, 'score': 0}, {'active': True, 'score': 0}]
若要改為建立多個空字典,請在每次迭代時呼叫 dict():
records = [dict() for _ in range(3)]
print(records)
[{}, {}, {}]
串列推導式也能根據可迭代物件產生欄位值:
records = [{"id": number, "label": f"item-{number}"} for number in range(3)]
print(records)
[{'id': 0, 'label': 'item-0'}, {'id': 1, 'label': 'item-1'}, {'id': 2, 'label': 'item-2'}]
不要用乘法重複包含單一可變字典的串列來建立多筆資料。例如,[{}] * 3 會重複參照同一個字典,因此修改其中一個元素時,三個位置都會顯示這項變更。使用 {} 的串列推導式則會在每次迭代建立新的字典。
在迴圈中建立字典
如果每個字典需要經過多個步驟,或包含條件式欄位,可以使用迴圈。在每次迭代中建立新的字典,再將它附加至串列。
本節中的程式碼以及顯示的標籤或輸出仍為英文。
records = []
for number in range(3):
record = {"id": number, "score": number * 10}
records.append(record)
for record in records:
print(record)
{'id': 0, 'score': 0}
{'id': 1, 'score': 10}
{'id': 2, 'score': 20}
在此範例中,迴圈每執行一次,就會使用當前的 number 建立一筆資料;接著 append() 會在進入下一次迭代前,將該字典存入串列。
使用 dict() 建構子建立字典
不帶引數呼叫 dict() 會建立空字典,也可以用關鍵字欄位建立字典。關鍵字名稱會成為字串鍵:
本節中的程式碼以及顯示的標籤或輸出仍為英文。
blank_record = dict()
person = dict(name="John", age=30, city="New York")
print(blank_record)
print(person)
{}
{'name': 'John', 'age': 30, 'city': 'New York'}
你可以分別呼叫 dict(),在串列中建立多個字典:
records = [
dict(name="Ada", role="engineer"),
dict(name="Lin", role="designer"),
]
for record in records:
print(record)
{'name': 'Ada', 'role': 'engineer'}
{'name': 'Lin', 'role': 'designer'}
字典的鍵必須是可雜湊的型別,例如字串、數字,以及由可雜湊值組成的元組;串列等可變型別不能作為鍵。每個鍵在字典中最多只能出現一次。如果以重複的鍵值組建立字典,後面的值會取代前面的值。使用 dict() 的關鍵字引數時,同一個呼叫中的每個關鍵字只能出現一次;若輸入可能有重複鍵,請改用映射或鍵值配對序列。