📜  Python程序获取每个键字典列表的最大值

📅  最后修改于: 2022-05-13 01:54:40.367000             🧑  作者: Mango

Python程序获取每个键字典列表的最大值

给定字典列表,编写一个Python程序来获取每个键的最大值。

例子:

方法 #1:使用items() + loop + max()

在这种情况下,我们使用循环迭代每个字典和其中的键,并使用 max() 不断更新每个键的最大值。

Python3
# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using items() + loop + max()
  
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
  
res = {}
for dic in test_list:
    for key, val in dic.items():
  
        # checking for key presence and updating max
        if key in res:
            res[key] = max(res[key], val)
        else:
            res[key] = val
  
# printing result
print("All keys maximum : " + str(res))


Python3
# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using defaultdict()
from collections import defaultdict
  
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
  
res = defaultdict(int)
for dic in test_list:
    for key, val in dic.items():
  
        # defaultdict helps to avoid conditional check here
        res[key] = max(res[key], val)
  
# printing result
print("All keys maximum : " + str(dict(res)))


输出:

方法 #2:使用defaultdict()

在这里,我们通过使用 defaultdict() 省略了条件检查密钥存在的步骤。其余的所有功能都与上述方法类似。

蟒蛇3

# Python3 code to demonstrate working of
# All Keys Maximum in Dictionary List
# Using defaultdict()
from collections import defaultdict
  
# initializing Matrix
test_list = [{"Gfg": 8, "is": 1, "Best": 9},
             {"Gfg": 2, "is": 9, "Best": 1},
             {"Gfg": 5, "is": 10, "Best": 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
  
res = defaultdict(int)
for dic in test_list:
    for key, val in dic.items():
  
        # defaultdict helps to avoid conditional check here
        res[key] = max(res[key], val)
  
# printing result
print("All keys maximum : " + str(dict(res)))

输出: