在 Python 中將兩個列表轉換為字典
在 Python 中列表包含一系列值,而字典包含兩組值,稱為鍵值對。在本文中,我們將採用兩個列表並將它們標記在一起以建立一個 Python 字典。
以 for 和 remove 方式
我們將建立兩個巢狀 for 迴圈。在內部迴圈中將分配一個列表作為字典的鍵,同時不停地逐個移除外部 for 迴圈中列表中的值。
示例
listK = ["Mon", "Tue", "Wed"] listV = [3, 6, 5] # Given lists print("List of K : ", listK) print("list of V : ", listV) # Empty dictionary res = {} # COnvert to dictionary for key in listK: for value in listV: res[key] = value listV.remove(value) break print("Dictionary from lists :\n ",res)
輸出
執行以上程式碼會得到以下結果 −
('List of K : ', ['Mon', 'Tue', 'Wed']) ('list of V : ', [3, 6, 5]) ('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
以 for 和 range 方式
將兩個列表組合起來,透過將它們放入 for 迴圈中來建立鍵值對。range 和 len 函式用於跟蹤元素的數量,直到建立所有鍵值對。
示例
listK = ["Mon", "Tue", "Wed"] listV = [3, 6, 5] # Given lists print("List of K : ", listK) print("list of V : ", listV) # COnvert to dictionary res = {listK[i]: listV[i] for i in range(len(listK))} print("Dictionary from lists :\n ",res)
輸出
執行以上程式碼會得到以下結果 −
('List of K : ', ['Mon', 'Tue', 'Wed']) ('list of V : ', [3, 6, 5]) ('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
以 zip 方式
zip 函式執行的操作與上述方法類似。它還將兩個列表中的元素組合起來,建立鍵值對。
示例
listK = ["Mon", "Tue", "Wed"] listV = [3, 6, 5] # Given lists print("List of K : ", listK) print("list of V : ", listV) # COnvert to dictionary res = dict(zip(listK, listV)) print("Dictionary from lists :\n ",res)
輸出
執行以上程式碼會得到以下結果 −
('List of K : ', ['Mon', 'Tue', 'Wed']) ('list of V : ', [3, 6, 5]) ('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
廣告