Python程序获取每个键字典列表的最大值
给定字典列表,编写一个Python程序来获取每个键的最大值。
例子:
Input : test_list = [{“Gfg” : 8, “is” : 1, “Best” : 9}, {“Gfg” : 2, “is” : 9, “Best” : 1}, {“Gfg” : 5, “is” : 10, “Best” : 7}]
Output : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}
Explanation : Maximum of Gfg key is 8 among possible 8, 2 and 5.
Input : test_list = [{“Gfg” : 8, “is” : 1, “Best” : 9}, {“Gfg” : 5, “is” : 10, “Best” : 7}]
Output : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}
Explanation : Maximum of Best key is 7 among possible 9, 7.
方法 #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)))
输出:
The original list is : [{‘Gfg’: 8, ‘is’: 1, ‘Best’: 9}, {‘Gfg’: 2, ‘is’: 9, ‘Best’: 1},
{‘Gfg’: 5, ‘is’: 10, ‘Best’: 7}]
All keys maximum : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}The original list is : [{‘Gfg’: 8, ‘is’: 1, ‘Best’: 9},
{‘Gfg’: 2, ‘is’: 9, ‘Best’: 1}, {‘Gfg’: 5, ‘is’: 10, ‘Best’: 7}]
All keys maximum : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}
方法 #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)))
输出:
The original list is : [{‘Gfg’: 8, ‘is’: 1, ‘Best’: 9}, {‘Gfg’: 2, ‘is’: 9, ‘Best’: 1},
{‘Gfg’: 5, ‘is’: 10, ‘Best’: 7}]
All keys maximum : {‘Gfg’: 8, ‘is’: 10, ‘Best’: 9}