Python:对dict的值进行排序并提取与最后n个值对应的键

标签 python sorting dictionary

假设您有一个这样的字典,但不一定按其值排序:
d={a:2,k:2,c:11,f:17,e:84,y:86}
并且您想将值从大到小排序:
order=sorted(d.values(),reverse=True)
这会给你:
order=[86,84,17,11,2,2]
现在,让我们取最后两个元素:
b=order[-2:]=[2,2]
检索 d 中与 b 中的值对应的键的 Pythonic 方法是什么? 在这种情况下,预期的结果是:
ans=[a,k]

最佳答案

使用 key sorted() 参数获取按值排序的键列表:

>>> d = {'a': 2, 'k': 2, 'c': 11, 'f': 17, 'e': 84, 'y': 86}
>>> sorted(d, key=d.get)[:2]
['a', 'k']

引用文档:

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).



或者,(如果 n 很小)您可以使用 heapq.nsmallest ,这样可以避免对所有键进行排序:
>>> from heapq import nsmallest
>>> nsmallest(2, d, key=d.get)
['a', 'k']

关于Python:对dict的值进行排序并提取与最后n个值对应的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40488532/

相关文章:

node.js - Couchbase 查看 : get documents by keys, 已排序

ios - 俱乐部对象数组

python - 用多个字典值替换字符串中的单词?

pandas - 来自 Dict 的 Panda Dataframe 具有不同的长度值

python - 如何使用临时环境变量运行脚本?

python - 在 Graphviz 中删除一个节点

python - 从 python 脚本运行 shell 命令\n

java - 这是一种新的排序算法吗? [使用 Java 和伪代码实现]

javascript - 有没有创建 map 的快捷方法?

python - OpenCV 模板匹配 True/False