Python – 將元組連線到字典鍵


當需要連線元組到字典鍵時,就使用列表解析和“join”屬性。

示例

以下是相關示例說明 −

my_list = [(("pyt", "is", "best"), 10), (("pyt", "cool"), 1), (("pyt", "is", "fun"), 15)]

print("The list is :")
print(my_list)

my_result = {}
for sub_list in my_list:

   my_result[" ".join(sub_list[0])] = sub_list[1]

print("The result is :")
print(my_result)

輸出

The list is :
[(('pyt', 'is', 'best'), 10), (('pyt', 'cool'), 1), (('pyt', 'is', 'fun'), 15)]
The result is :
{'pyt is best': 10, 'pyt cool': 1, 'pyt is fun': 15}

說明

  • 定義了一個元組列表,並在控制檯上顯示。

  • 建立了一個空字典。

  • 對列表進行迭代,並使用列表解析來去除空格。

  • 這是在控制檯上顯示的輸出。

更新於:08-Sep-2021

325 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

入門
廣告
© . All rights reserved.