Python 列表轉換為字典列表


Python 中的資料處理、組織或結構化有很多常見的任務,其中一項任務是將列表轉換為字典列表。這是一個簡單的過程,允許我們將特定的鍵與其對應的值關聯起來;建立一個易於訪問和/或操作的字典集合。

在繼續講解技術之前,讓我們首先看一個輸入和輸出示例。

輸入

test_list = ['John', 25, 'Smith', 30, 'Alice', 35]
key_list = ['name', 'age']

輸出

[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]

方法一:使用迴圈

在這種方法中,我們簡單地獲取一個包含交替名稱和年齡的列表,並將其轉換為字典列表,其中每個生成的字典列表都代表一個人的資訊,併為“姓名”和“年齡”提供鍵。透過對原始列表進行迴圈迭代,然後根據提供的鍵對值進行分組。建立的字典被附加到列表“result”中。

示例

test_list = ['John', 25, 'Smith', 30, 'Alice', 35]
key_list = ['name', 'age']

result = []
for i in range(0, len(test_list), len(key_list)):
   temp_dict = {}
   for j, key in enumerate(key_list):
      temp_dict[key] = test_list[i + j]
   result.append(temp_dict)

print(result)

輸出

[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]

方法二:使用帶 zip() 的列表推導式

這是另一種實現目標的方法,它使用列表推導式將列表轉換為字典列表。它以 key_list 的長度確定的塊為單位迭代 test_list,從而建立字典,這些字典與來自 key_list 的元素及其來自 test_list 切片的對應元素配對。然後,它最終將它們附加到結果列表,這是一個字典列表。zip() 函式負責元素的配對。

示例

test_list = ['John', 25, 'Smith', 30, 'Alice', 35]
key_list = ['name', 'age']

result = [{key: value for key, value in zip(key_list, test_list[i:i+len(key_list)])} for i in range(0, len(test_list), len(key_list))]

print(result)

輸出

[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]

方法三:使用帶切片的列表推導式

此方法還使用列表推導式以 key_list 的長度為增量迭代 test_list(在程式碼開頭建立)。在列表推導式中,我們有一個字典推導式,它透過使用索引將來自 key_list 的鍵與 test_list 中的值配對來建立字典。

示例

test_list = ['John', 25, 'Smith', 30, 'Alice', 35]
key_list = ['name', 'age']

result = [{key_list[j]: test_list[i+j] for j in range(len(key_list))} for i in range(0, len(test_list), len(key_list))]
print(result)

輸出

[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]

方法四:使用 Itertools.islice() 和 Iter()

在 Python 中,通常使用 itertools 進行迭代。其函式之一 islice() 允許我們透過指定起始和結束索引來提取可迭代物件的特定部分。透過使用 iter(test_list),我們可以為 test_list 建立一個迭代器。然後,此迭代器可以與 islice() 一起使用,以從 test_list 中提取特定數量的元素。

zip 函式將切片元素與 key_list 組合。然後,使用字典推導式建立字典。需要注意的是,以下程式碼中的迭代次數由公式決定:length(test_list) 除以 length(key_list)。

示例

import itertools

test_list = ['John', 25, 'Smith', 30, 'Alice', 35]
key_list = ['name', 'age']

iter_test = iter(test_list)
result = [{key: value for key, value in zip(key_list, itertools.islice(iter_test, len(key_list)))} for _ in range(len(test_list) // len(key_list))]

print(result)

輸出

[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]

方法五:使用生成器函式

生成器函式是一種可以生成一系列值並一次一個地生成它們的功能;允許高效的記憶體使用。yield 關鍵字用於生成值,並且可以使用簡單的迴圈遍歷該函式。以下方法定義了一個名為 generate_dicts 的生成器,它將 test_list 和 key_list 作為輸入。字典是透過將來自 key_list 的元素與其在 test_list 中的對應元素配對來生成的。

示例

def generate_dicts(test_list, key_list):
   for i in range(0, len(test_list), len(key_list)):
      yield {key_list[j]: test_list[i+j] for j in 
# yield keyword instead of return
range(len(key_list))}

test_list = ['John', 25, 'Smith', 30, 'Alice', 35]
key_list = ['name', 'age']

result = list(generate_dicts(test_list, key_list))
print(result)

輸出

[{'name': 'John', 'age': 25}, {'name': 'Smith', 'age': 30}, {'name': 'Alice', 'age': 35}]

結論

在本文中,我們發現了在 Python 中將列表轉換為字典列表的不同方法。這些方法包括使用迴圈;帶 zip() 的列表推導式;帶切片的列表推導式;itertools.islice() 和 iter(),最後是生成器函式。所有這些方法都為我們提供了將資料轉換為結構化格式的靈活性。所有方法的時間複雜度都是 O(n)。

更新於:2023年8月18日

瀏覽量 261

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告