在字典中按值排序

时间:2017-06-12 10:57:36

标签: python dictionary

我只是练习python。我有一个字典:

my_dict = [{'word': 'aa', 'value': 2}, 
           {'word': 'aah', 'value': 6}, 
           {'word': 'aahed', 'value': 9}]

如何订购这本词典,如果我有数千个单词,那么我可以根据它们的价值排名选择前100名?例如,仅从上面的例子:

scrabble_rank = [{'word': 'aahed', 'rank': 1},
                 {'word': 'aah', 'rank': 2}, 
                 {'word': 'aa', 'rank': 3}]

4 个答案:

答案 0 :(得分:3)

首先,那不是字典;这是一个词典列表。哪个好,因为字典是无序的,但列表是有序的。

您可以使用rank元素的值作为排序函数的键来对列表进行排序:

scrabble_rank.sort(key=lambda x: x['value'])

答案 1 :(得分:0)

这就是你要找的东西:

scrabble_rank = [{'word':it[1], 'rank':idx+1} for idx,it in enumerate(sorted([[item['value'],item['word']] for item in my_dict],reverse=True))]

答案 2 :(得分:0)

使用Pandas资料库:

import pandas as pd

有这个单行:

scrabble_rank = pd.DataFrame(my_dict).sort_values('value', ascending=False).reset_index(drop=True).reset_index().to_dict(orient='records')

输出:

[{'index': 0, 'value': 9, 'word': 'aahed'},
 {'index': 1, 'value': 6, 'word': 'aah'},
 {'index': 2, 'value': 2, 'word': 'aa'}]

基本上它会将您的记录读入DataFrame,然后按value降序排序,然后删除原始索引(订单),并将其导出为记录(您之前的格式)。

答案 3 :(得分:0)

您可以使用heapq

import heapq

my_dict = [{'word': 'aa', 'value': 2}, 
           {'word': 'aah', 'value': 6}, 
           {'word': 'aahed', 'value': 9}]

# Select the top 3 records based on `value`
values_sorted = heapq.nlargest(3, # fetch top 3
                               my_dict, # dict to be used
                               key=lambda x: x['value']) # Key definition
print(values_sorted)
[{'word': 'aahed', 'value': 9}, {'word': 'aah', 'value': 6}, {'word': 'aa', 'value': 2}]