Python、辞書を指定すると、キーまたは値に基づいて並べ替えを実行します。 [ 該当する Python>=3.6v ]。
入力 : test_dict = {Gfg : 5、is : 7、Best : 2} 出力 : {「ベスト」: 2, 「Gfg」: 5, 「is」: 7}, {「is」: 7, 「Gfg」: 5, 「ベスト」: 2} 説明 : キーによって昇順および逆順にソートされます。 入力 : test_dict = {ベスト : 2、for : 9、geeks : 8} 出力 : {「ベスト」: 2, 「Gfg」: 5, 「for」: 9}, {「for」: 9, 「オタク」: 8, 「ベスト」: 2} 説明 : 値によって昇順および逆順に並べ替えられます。
ケース 1 : キーによる並べ替え
このタスクはsorted()を使用して実行されます。ここでは、items()で抽出された辞書の項目の最初のインデックスを使用してキーを抽出し、それをカスタムラムダ関数としてkeyに渡してキーでソートします。逆ソートを実行するには、reverse=True を追加します。
Python3
Javaは文字列をintに変換します
# Python3 code to demonstrate working of> # Sort a Dictionary> # Sort by Keys> # initializing dictionary> test_dict> => {> 'Gfg'> :> 5> ,> 'is'> :> 7> ,> 'Best'> :> 2> ,> 'for'> :> 9> ,> 'geeks'> :> 8> }> # printing original dictionary> print> (> 'The original dictionary is : '> +> str> (test_dict))> # using items() to get all items> # lambda function is passed in key to perform sort by key> res> => {key: val> for> key, val> in> sorted> (test_dict.items(), key> => lambda> ele: ele[> 0> ])}> # printing result> print> (> 'Result dictionary sorted by keys : '> +> str> (res))> # using items() to get all items> # lambda function is passed in key to perform sort by key> # adding 'reversed = True' for reversed order> res> => {key: val> for> key, val> in> sorted> (test_dict.items(), key> => lambda> ele: ele[> 0> ], reverse> => True> )}> # printing result> print> (> 'Result dictionary sorted by keys ( in reversed order ) : '> +> str> (res))> |
>
>出力
The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8} Result dictionary sorted by keys : {'Best': 2, 'Gfg': 5, 'for': 9, 'geeks': 8, 'is': 7} Result dictionary sorted by keys ( in reversed order ) : {'is': 7, 'geeks': 8, 'for': 9, 'Gfg': 5, 'Best': 2}>
ケース 2 : 値による並べ替え
このタスクは上記と同様の方法で実行できますが、唯一の違いは値の抽出であり、 items() の 2 番目の要素がコンパレータとして渡されることです。
Python3
パイソンが含まれています
# Python3 code to demonstrate working of> # Sort a Dictionary> # Sort by Values> # initializing dictionary> test_dict> => {> 'Gfg'> :> 5> ,> 'is'> :> 7> ,> 'Best'> :> 2> ,> 'for'> :> 9> ,> 'geeks'> :> 8> }> # printing original dictionary> print> (> 'The original dictionary is : '> +> str> (test_dict))> # using items() to get all items> # lambda function is passed in key to perform sort by key> # passing 2nd element of items()> res> => {key: val> for> key, val> in> sorted> (test_dict.items(), key> => lambda> ele: ele[> 1> ])}> # printing result> print> (> 'Result dictionary sorted by values : '> +> str> (res))> # using items() to get all items> # lambda function is passed in key to perform sort by key> # passing 2nd element of items()> # adding 'reversed = True' for reversed order> res> => {key: val> for> key, val> in> sorted> (test_dict.items(), key> => lambda> ele: ele[> 1> ], reverse> => True> )}> # printing result> print> (> 'Result dictionary sorted by values ( in reversed order ) : '> +> str> (res))> |
>
セレンの基本
>出力
The original dictionary is : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8} Result dictionary sorted by values : {'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9} Result dictionary sorted by values ( in reversed order ) : {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}>
方法#3:collections.OrderedDict() とsorted() を使用する
アプローチ
このアプローチでは、sorted() 関数を使用して、値に基づいて辞書を昇順または降順に並べ替えます。 sorted() 関数は、辞書の items() メソッドと、各タプルの 2 番目の要素 (値) またはその否定を返すキー関数を使用して呼び出されます。結果のタプルのリストは OrderedDict() コンストラクターに渡され、元の辞書と同じキーと値のペアを持ち、値でソートされた新しい順序付き辞書が作成されます。
アルゴリズム
1. 辞書「test_dict」でsorted()関数を呼び出し、ラムダ関数を「key」引数として渡します。
2. lambda 関数は、各キーと値のペアを入力として受け取り、希望の順序に応じて並べ替えの基準となるキーまたは値を返します。
3.sorted() 関数を使用して、ソートされたキーと値のペアのリストを返します。
4. 並べ替えられたリストを OrderedDict() コンストラクターに渡し、新しい順序付き辞書を作成します。
5. 注文された辞書を返します。
Python3
from> collections> import> OrderedDict> from> operator> import> itemgetter> def> sort_dict_by_value(test_dict):> > sorted_list> => sorted> (test_dict.items(), key> => itemgetter(> 1> ))> > return> OrderedDict(sorted_list)> def> sort_dict_by_value_reverse(test_dict):> > sorted_list> => sorted> (test_dict.items(), key> => itemgetter(> 1> ), reverse> => True> )> > return> OrderedDict(sorted_list)> test_dict> => {> 'Gfg'> :> 5> ,> 'is'> :> 7> ,> 'Best'> :> 2> ,> 'for'> :> 9> ,> 'geeks'> :> 8> }> print> (sort_dict_by_value(test_dict))> print> (sort_dict_by_value_reverse(test_dict))> |
>
「メイソンの公式」
>出力
OrderedDict([('Best', 2), ('Gfg', 5), ('is', 7), ('geeks', 8), ('for', 9)]) OrderedDict([('for', 9), ('geeks', 8), ('is', 7), ('Gfg', 5), ('Best', 2)])>
時間計算量: O(N log N)、N は辞書内のキーと値のペアの数です。
スペースの複雑さ: O(N)、並べ替えられたキーと値のペアを格納するための新しい順序付き辞書を作成しているため。
方法 4 : キー パラメーターとしてラムダ関数を指定して、sorted() メソッドを使用します。
手順は次のとおりです。
- ソートする辞書を定義します。
- 辞書を値で並べ替えるには、sorted() メソッドを使用します。
- ラムダ関数をキーパラメータとしてsorted()メソッドに渡し、値によって並べ替えを行うように指定します。
- dict() コンストラクターを使用して、ソートされたタプルのリストから新しい辞書を作成します。
Python3
def> sort_dict_by_value_lambda(test_dict):> > sorted_list> => sorted> (test_dict.items(), key> => lambda> x: x[> 1> ])> > return> dict> (sorted_list)> def> sort_dict_by_value_lambda_reverse(test_dict):> > sorted_list> => sorted> (test_dict.items(), key> => lambda> x: x[> 1> ], reverse> => True> )> > return> dict> (sorted_list)> test_dict> => {> 'Gfg'> :> 5> ,> 'is'> :> 7> ,> 'Best'> :> 2> ,> 'for'> :> 9> ,> 'geeks'> :> 8> }> print> (sort_dict_by_value_lambda(test_dict))> print> (sort_dict_by_value_lambda_reverse(test_dict))> |
YouTubeビデオVLCをダウンロードする方法
>
>出力
{'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9} {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}>
時間計算量: O(n log n) ここで、n は辞書内の項目の数です。
補助スペース: ソートされたタプルのリストを格納するための O(n)。 dict() コンストラクターは、ソートされたリストから新しい辞書を作成するのに O(n) 時間かかります。