我有字典:
{ "key1" : 1, "key2" : 2, ...., "key100" : 100 }
我想通过此词典中的排序值获取列表top5键:
[ "key100", "key99",.. "key95" ]
怎么做?
答案 0 :(得分:4)
只需使用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']
答案 1 :(得分:1)
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个值的列表。这是你想要的吗?
答案 2 :(得分:0)
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']