Python 程式獲取字典列表每個鍵的最大值


如果需要獲取字典元素列表中每個鍵的最大值,可以使用簡單迭代。

範例

以下是對其進行演示

my_list = [{"Hi": 18, "there": 13, "Will": 89},
   {"Hi": 53, "there": 190, "Will": 87}]

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

my_result = {}
for elem in my_list:
   for key, val in elem.items():
      if key in my_result:
         my_result[key] = max(my_result[key], val)
      else:
         my_result[key] = val

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

輸出結果

The list is :
[{'Will': 89, 'there': 13, 'Hi': 18}, {'Will': 87, 'there': 190, 'Hi': 53}]
The result is :
{'Will': 89, 'there': 190, 'Hi': 53}

說明

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

  • 定義了一個空字典。

  • 迭代列表,並訪問元素。

  • 如果鍵存在於之前定義的字典中,則確定鍵值的最大值,並存儲在字典的“key”索引中。

  • 否則,該值儲存在字典的“key”索引中。

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

更新於:16-Sep-2021

180 次瀏覽

開啟職業生涯

完成課程後即可獲得認證

開始學習
廣告
© . All rights reserved.