提取N个最大字典键的Python程序
给定一个字典,按降序提取最大的 N 个字典键。
Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 3
Output : [10, 8, 6]
Explanation : Max. N keys extracted in descending order.
Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 2
Output : [10, 8]
Explanation : Max. N keys extracted in descending order.
方法 #1:使用 sorted() + lambda + reverse
以上功能的组合可以解决这个问题。在此,我们使用 sorted() + lambda 执行按键排序,而 reverse 用于执行反向排序以获得所需的排序。
Python3
# Python3 code to demonstrate working of
# Extract top N Dictionaries by Key
# Using sorted() + lambda + reverse
# initializing dictionary
test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing N
N = 4
res = []
# 0 in lambda used for keys, list sliced till N for top N values
for key, val in sorted(test_dict.items(), key = lambda x: x[0], reverse = True)[:N]:
res.append(key)
# printing result
print("Top N keys are: " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract top N Dictionaries by Key
# Using nlargest() + lambda
from heapq import nlargest
# initializing dictionary
test_dict = {6 : 2, 8: 9, 3: 9, 6: 1, 10: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing N
N = 4
res = []
# Using nlargest() to get maximum keys
for key, val in nlargest(N, test_dict.items(), key = lambda ele: ele[0]):
res.append(key)
# printing result
print("Top N keys are: " + str(res))
输出
The original dictionary is : {6: 1, 8: 9, 3: 9, 10: 8}
Top N keys are: [10, 8, 6, 3]
方法 #2:使用 nlargest() + lambda
这是可以执行此任务的另一种方式。其中,使用 nlargest() 提取最大值,并使用 lambda函数来驱动键提取和比较逻辑。
蟒蛇3
# Python3 code to demonstrate working of
# Extract top N Dictionaries by Key
# Using nlargest() + lambda
from heapq import nlargest
# initializing dictionary
test_dict = {6 : 2, 8: 9, 3: 9, 6: 1, 10: 8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing N
N = 4
res = []
# Using nlargest() to get maximum keys
for key, val in nlargest(N, test_dict.items(), key = lambda ele: ele[0]):
res.append(key)
# printing result
print("Top N keys are: " + str(res))
输出
The original dictionary is : {6: 1, 8: 9, 3: 9, 10: 8}
Top N keys are: [10, 8, 6, 3]