Python 中將元組列表轉換成字典
在本文中,我們將學習如何將元組列表轉換為字典。將元組列表轉換為字典是一件很直觀的事情。
按照以下步驟完成程式碼。
- 使用元組對列表進行初始化。
- 使用 dict 將給定的元組列表轉換為字典。
- 列印結果字典。
示例
我們來看看程式碼。
# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]
# converting to dict
result = dict(tuples)
# printing the result
print(result)如果你執行上面程式碼,你將得到以下結果。
輸出
{'Key 1': 1, 'Key 2': 2, 'Key 3': 3, 'Key 4': 4, 'Key 5': 5}
讓我們使用 setdefault() 方法在結果字典中新增值作為列表。
按照以下步驟完成程式碼。
- 使用元組對列表進行初始化。
- 遍歷元組列表。
- 設定鍵的預設值並新增值。
- 列印結果。
示例
我們來看看程式碼。
# initializing the list
tuples = [('Key 1', 1), ('Key 2', 2), ('Key 3', 3), ('Key 4', 4), ('Key 5', 5)]
# result
result = {}
# iterating over the tuples lists
for (key, value) in tuples:
# setting the default value as list([])
# appending the current value
result.setdefault(key, []).append(value)
# printing the list
print(result)如果你執行上面程式碼,你將得到以下結果。
輸出
{'Key 1': [1], 'Key 2': [2], 'Key 3': [3], 'Key 4': [4], 'Key 5': [5]}
總結
如果你對文章有任何疑問,可以在評論部分提出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP