回答編集履歴

1

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

2018/09/26 07:57

投稿

takey
takey

スコア312

test CHANGED
@@ -41,3 +41,53 @@
41
41
  print(new_dict)
42
42
 
43
43
  ```
44
+
45
+
46
+
47
+ Nが小さいならば、[heapq.nlargest モジュール](https://docs.python.jp/3/library/heapq.html#heapq.nlargest)を使ったほうが高速です。
48
+
49
+
50
+
51
+
52
+
53
+ ```python
54
+
55
+ # coding: utf-8
56
+
57
+ import heapq
58
+
59
+
60
+
61
+ N = 3
62
+
63
+ d = {'key1': 1,'key2': 14,'key3': 47,'key4': 2,'key5': 90}
64
+
65
+
66
+
67
+ # keyでソートしたときの上位N個
68
+
69
+ lists = heapq.nlargest(N, d.items(), key=lambda x: x[0])
70
+
71
+ new_dict = {}
72
+
73
+ for l in lists:
74
+
75
+ new_dict[l[0]] = l[1]
76
+
77
+ print(new_dict)
78
+
79
+
80
+
81
+ # valueでソートしたときの上位N個
82
+
83
+ lists = heapq.nlargest(N, d.items(), key=lambda x: x[1])
84
+
85
+ new_dict = {}
86
+
87
+ for l in lists:
88
+
89
+ new_dict[l[0]] = l[1]
90
+
91
+ print(new_dict)
92
+
93
+ ```