利用 Python 中列表內容建立字典
在 python 中頻繁需要將集合型別從一種型別更改為另一種型別。本文將介紹如何利用多個給定列表建立字典。挑戰在於能夠合併所有這些列表,以將所有這些值組合在一個字典鍵值格式中。
利用 zip
zip 函式可用於合併不同列表的值,如下所示。在下面的示例中,我們接受了三個列表作為輸入,並將它們組合形成一個字典。其中一個列表提供字典的鍵,而其他兩個列表則儲存對應於每個鍵的值欄位。
示例
key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']
# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))
# Dictionary creation
res = {key: {'Day': day, 'Fruit': fruit} for key, day, fruit in
zip(key_list, day_list, fruit_list)}
# Result
print("The final dictionary : \n" ,res)輸出
執行以上程式碼將獲得以下結果 -
Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'Fruit': 'Apple'}, 2: {'Day': 'Saturday', 'Fruit': 'Banana'}, 3: {'Day': 'Sunday', 'Fruit': 'Grape'}}利用 enumerate
enumerate 函式將計數器新增到 enumerate 物件的鍵。因此,在我們的示例中,我們將向
示例
key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']
# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))
# Dictionary creation
res = {val : {"Day": day_list[key], "age": fruit_list[key]}
for key, val in enumerate(key_list)}
# Result
print("The final dictionary : \n" ,res)輸出
執行以上程式碼將獲得以下結果 -
Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'age': 'Apple'}, 2: {'Day': 'Saturday', 'age': 'Banana'}, 3: {'Day': 'Sunday', 'age': 'Grape'}}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP