简体   繁体   English

如何获得字典中最大的 n 个值但保留 position

[英]how to get the largest n values in the dictionary but keep the position

The original dictionary is:原来的字典是:

{'gfg': 1, 'best': 6, 'geeks': 3, 'for': 7, 'is': 4}

The top N = 3 value pairs are ['for', 'best', 'is'] (sorted by value) but I need ['best', 'for', 'is'] (original dictionary order).N = 3值对是['for', 'best', 'is'] (按值排序)但我需要['best', 'for', 'is'] (原始字典顺序)。

Dictionaries are insertion ordered, but we can't really talk about a position. An acceptable solution could be:字典是按插入顺序排列的,但我们不能真正谈论 position。可接受的解决方案可能是:

>>> d = {'gfg': 1, 'best': 6, 'geeks': 3, 'for': 7, 'is': 4}
>>> cutoff = sorted(d.values())[-3]
>>> [k for k, v in d.items() if v >= cutoff][:3]
['best', 'for', 'is']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM