如何通过值从dict中获取键的顶部?

2024-05-15 05:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有字典:

{ "key1" : 1, "key2" : 2, ...., "key100" : 100 }

我想从这本词典中按排序值列出前5个键:

[ "key100", "key99",.. "key95" ]

怎么做?你知道吗


Tags: 字典排序key2key1key99本词典个键key95
3条回答
d = { "key1" : 1, "key2" : 2, ...., "key100" : 100 }
a = sorted(d.values())
a.reverse()
req_list = []
for i in a[:5]:
    req_list.append(d.keys()[d.values().index(i)])

print req_list

这将为您提供5个最大值的列表。这是你想要的吗?你知道吗

只需使用lambda函数对键进行排序,将值作为键返回,反转,然后取前5个值:

d={ "key1" : 1, "key2" : 2, "key3" : 3, "key200" : 200 , "key100" : 100 , "key400" : 400}


print(sorted(d.keys(),reverse=True,key=lambda x : d[x] )[:5])

输出:

['key400', 'key200', 'key100', 'key3', 'key2']
Python 2.7.10 (default, Oct 23 2015, 19:19:21)

>>> d = {"key1": 1, "key2": 2, "key3": 3, "key98": 98 , "key99": 99 , "key100": 100}

>>> sorted(d, reverse=True, key=d.get)[:3]
['key100', 'key99', 'key98']

相关问题 更多 >

    热门问题