📜  Python – 提取最大键的值字典

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

Python – 提取最大键的值字典

给定一个字典,在字典列表中的其他键中提取包含具有最大值的任何键的所有字典。

方法:使用 max() + filter() + lambda

上述功能的组合可以用来解决这个问题。在此,首先为特定键提取最大值,然后提取与最大键匹配的所有字典。这是对所有键执行的。

Python3
# Python3 code to demonstrate working of 
# Extract Maximum Keys' value dictionaries
# Using max() + filter() + lambda
  
# initializing list
test_list = [{"Gfg" : 3, "is" : 7, "Best" : 8}, 
             {"Gfg" : 9, "is" : 2, "Best" : 9}, 
             {"Gfg" : 5, "is" : 4, "Best" : 10},
             {"Gfg" : 3, "is" : 6, "Best" : 8}]
  
# printing original list
print("The original list : " + str(test_list))
  
res = []
  
# getting all keys 
all_keys = list(test_list[0].keys())
for sub in all_keys:
      
    # extracting maximum of each keys
    temp = max(test_list, key = lambda ele: ele[sub]) 
    res_key = list(filter(lambda ele: ele[sub] == temp[sub], test_list))
    res.append(res_key)
  
# printing result 
print("The extracted maximum key values dictionaries : " + str(res))


输出
The original list : [{'Gfg': 3, 'is': 7, 'Best': 8}, {'Gfg': 9, 'is': 2, 'Best': 9}, {'Gfg': 5, 'is': 4, 'Best': 10}, {'Gfg': 3, 'is': 6, 'Best': 8}]
The extracted maximum key values dictionaries : [[{'Gfg': 9, 'is': 2, 'Best': 9}], [{'Gfg': 3, 'is': 7, 'Best': 8}], [{'Gfg': 5, 'is': 4, 'Best': 10}]]