teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

heapq.nlargest についての説明を追加

2018/09/26 07:57

投稿

takey
takey

スコア312

answer CHANGED
@@ -19,4 +19,29 @@
19
19
  for i in range(N):
20
20
  new_dict[lists[i][0]] = lists[i][1]
21
21
  print(new_dict)
22
+ ```
23
+
24
+ Nが小さいならば、[heapq.nlargest モジュール](https://docs.python.jp/3/library/heapq.html#heapq.nlargest)を使ったほうが高速です。
25
+
26
+
27
+ ```python
28
+ # coding: utf-8
29
+ import heapq
30
+
31
+ N = 3
32
+ d = {'key1': 1,'key2': 14,'key3': 47,'key4': 2,'key5': 90}
33
+
34
+ # keyでソートしたときの上位N個
35
+ lists = heapq.nlargest(N, d.items(), key=lambda x: x[0])
36
+ new_dict = {}
37
+ for l in lists:
38
+ new_dict[l[0]] = l[1]
39
+ print(new_dict)
40
+
41
+ # valueでソートしたときの上位N個
42
+ lists = heapq.nlargest(N, d.items(), key=lambda x: x[1])
43
+ new_dict = {}
44
+ for l in lists:
45
+ new_dict[l[0]] = l[1]
46
+ print(new_dict)
22
47
  ```