Python - 合併包含重複鍵的字典列表


當需要合併具有重複鍵的字典列表時,遍歷字串中的鍵,並根據條件確定結果。

示例

以下是演示程式碼:

my_list_1 = [{"aba": 1, "best": 4}, {"python": 10, "fun": 15}, {"scala": "fun"}]

my_list_2 = [{"scala": 6}, {"python": 3, "best": 10}, {"java": 1}]

print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)
for i in range(0, len(my_list_1)):

   id_keys = list(my_list_1[i].keys())
   for key in my_list_2[i]:

      if key not in id_keys:
         my_list_1[i][key] = my_list_2[i][key]

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

輸出

The first list is :
[{'aba': 1, 'best': 4}, {'python': 10, 'fun': 15}, {'scala': 'fun'}]
The second list is :
[{'scala': 6}, {'python': 3, 'best': 10}, {'java': 1}]
The result is :
[{'aba': 1, 'best': 4, 'scala': 6}, {'python': 10, 'fun': 15, 'best': 10}, {'scala': 'fun', 'java': 1}]

說明

  • 定義了兩個字典列表,並在控制檯上顯示。

  • 遍歷字典列表,並訪問鍵。

  • 將這些鍵儲存在一個變數中。

  • 遍歷第二個字典列表,如果其中存在鍵在前一個變數中,則對兩個列表中的相關鍵求值。

  • 結果顯示在控制檯上。

更新於:2021-9-20

649 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告