Python – 字典值反轉為列表


當需要將字典值反轉為列表時,可以使用簡單的迭代表達法和“追加”方法。

以下是同一內容的演示 −

from collections import defaultdict
my_dict = {13: [12, 23], 22: [31], 34: [21], 44: [52, 31]}
print("The dictionary is :")
print(my_dict)
my_result = defaultdict(list)
for keys, values in my_dict.items():
   for val in values:
      my_result[val].append(keys)
print("The result is :")
print(dict(my_result))

輸出

The dictionary is :
{34: [21], 44: [52, 31], 13: [12, 23], 22: [31]}
The result is :
{52: [44], 31: [44, 22], 12: [13], 21: [34], 23: [13]}

說明

  • 將所需的軟體包匯入到環境中。

  • 定義一個字典並顯示在控制檯上。

  • 使用 defaultdict 建立一個空字典。

  • 訪問字典的元素並進行迭代。

  • 使用“追加”方法將值追加到空字典中。

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

更新於: 07-Sep-2021

281 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告