python - 在字典python中找到前k个最大的键

标签 python

假设我有一本字典:

{key1:value1........... keyn:valuen}

假设我想写一个函数

def return_top_k(dictionary, k):

    return list_of_keys_sorted   

什么是最有效的方法(就大 O 而言)来获取具有前 k 个值的键(保持顺序,即最高值的键出现在开头......等等。)

最佳答案

O(n log k):

import heapq

k_keys_sorted = heapq.nlargest(k, dictionary)

您可以使用 key 关键字参数来指定应该用作排序键的内容,例如:

k_keys_sorted_by_values = heapq.nlargest(k, dictionary, key=dictionary.get)

关于python - 在字典python中找到前k个最大的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266617/

相关文章:

python - PiecewiseCubicZero 和 PiecewiseLogCubicDiscount 之间的区别

python - 无法在 git 终端中运行 python?

python - 能源消耗最大化

python - LabelPropagation - 如何避免被零除?

python - 用 scipy 解决颂歌系统 - 如何引用不同的索引?

python - 如何在我的服务器上运行 python 脚本?

python - IPython 在运行后维护命名空间

python - Tensorflow 中的多个分类输入变量

python - 当函数需要成为一个类时

python - NumPy 的/科学的 : Memory consumption increases linearly per iteration