📜  Python – 字典中的最小 K 值

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

Python – 字典中的最小 K 值

很多时候,在使用Python字典时,我们可能会遇到一个特殊的问题,即在众多键中找到值的 K 最小值。在使用 Web 开发域时,这个问题很常见。让我们讨论几种可以执行此任务的方法。

方法#1: itemgetter() + items() + sorted()
上述方法的组合用于执行此特定任务。在此,我们只是对使用 itemgetter() 表示并使用 items() 访问的字典值进行排序。

# Python3 code to demonstrate working of
# Smallest K values in Dictionary
# Using sorted() + itemgetter() + items()
from operator import itemgetter
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'geeks' : 3 }
  
# Initialize K 
K = 2
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Smallest K values in Dictionary
# Using sorted() + itemgetter() + items()
res = dict(sorted(test_dict.items(), key = itemgetter(1))[:K])
  
# printing result
print("The minimum K value pairs are " + str(res))
输出 :
The original dictionary is : {'geeks': 3, 'is': 4, 'for': 7, 'best': 6, 'gfg': 1}
The minimum K value pairs are {'geeks': 3, 'gfg': 1}

方法 #2:使用nsmallest()
可以使用nsmallest函数执行此任务。这是 heapq 库中的内置函数,它在内部执行此任务,可用于在外部执行此任务。有只打印键而不是值的缺点。

# Python3 code to demonstrate working of
# Smallest K values in Dictionary
# Using nsmallest
from heapq import nsmallest
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'geeks' : 3 }
  
# Initialize K
K = 2
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Smallest K values in Dictionary
# Using nsmallest
res = nsmallest(K, test_dict, key = test_dict.get)
  
# printing result
print("The minimum K value pairs are " + str(res))
输出 :
The original dictionary is : {'geeks': 3, 'best': 6, 'is': 4, 'gfg': 1, 'for': 7}
The minimum K value pairs are ['gfg', 'geeks']