如何在 Python 中使用列表推導式建立字典?


透過在 Python 中使用 dict() 方法,我們可以使用列表推導式建立 Python 字典。dict() 方法的語法如下所示。以下是此方法的語法

dict(**kwarg)

關鍵字引數。我們可以傳遞一個或多個關鍵字引數。如果未傳遞任何關鍵字引數,則 dict() 方法將建立一個空字典物件。使用列表推導式建立字典的語法

dict(list_comprehension)

使用列表推導式建立字典

這裡不需要傳送多個關鍵字,而是需要將包含鍵值對的元組列表傳送到 dict() 方法。讓我們舉個例子,並使用列表推導式建立一個字典。

示例

dict_= dict([(chr(i), i) for i in range(100, 105)])
print('Output dictionary: ', dict_)
print(type(dict_))

輸出

Output dictionary:  {'d': 100, 'e': 101, 'f': 102, 'g': 103, 'h': 104}
<class 'dict'>

為了在列表推導式中迭代 for 迴圈,我們使用了 range() 方法。並且我們還使用了另一個 Python 內建函式 chr() 來獲取 Unicode 整數的字串表示形式。在輸出字典中,鍵由 Unicode 整數的字串表示形式建立,值由迴圈整數建立。

示例

這裡我們將兩個輸入列表“data1”和“data2”透過 Python 的 zip() 方法傳遞給列表推導式。此 zip() 方法基於 2 個輸入建立迭代器,最後使用列表推導式建立字典。

data1 = [1, 2, 3, 4, 5]
data2 = [10, 20, 30, 40, 50]
print('input list1: ', data1)
print('input list12: ', data2)

# create a dict using list comprehension
d = dict([(key, value) for key, value in zip(data1,data2)])
print('Output dictionary: ', d)
print(type(d))

輸出

input list1:  [1, 2, 3, 4, 5]
input list12:  [10, 20, 30, 40, 50]
Output dictionary:  {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
<class 'dict'>

示例

在下面的示例中,使用 Python 列表推導式技術,我們建立了一個元組列表,每個元組包含 2 個元素。然後將這兩個元素轉換為字典物件的鍵和值。

l = [( i,i*2) for i in range(1,10)]
print("Comprehension output:",l)

dict_= dict(l)
print('Output dictionary: ', dict_)
print(type(dict_))

輸出

Comprehension output: [(1, 2), (2, 4), (3, 6), (4, 8), (5, 10), (6, 12), (7, 14), (8, 16), (9, 18)]
Output dictionary:  {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
<class 'dict'>

示例

最後,讓我們再舉一個例子,看看如何在 Python 中使用列表推導式建立字典。

l = [20, 21, 65, 29, 76, 98, 35]
print('Input list: ', l)

# create a dict using list comprehension
d = dict([(val/2, val) for val in l])
print('Output dictionary: ', d)
print(type(d))

輸出

Input list:  [20, 21, 65, 29, 76, 98, 35]
Output dictionary:  {10.0: 20, 10.5: 21, 32.5: 65, 14.5: 29, 38.0: 76, 49.0: 98, 17.5: 35}
<class 'dict'>

透過使用列表推導式迭代列表元素,我們成功建立了一個字典。

更新於: 2023-08-24

495 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.