Python, dato un dizionario, esegue l'ordinamento in base a chiavi o valori. [ Python applicabile>=3.6v ].
Ingresso : test_dict = {Gfg: 5, è: 7, Migliore: 2} Produzione : {'Migliore': 2, 'Gfg': 5, 'is': 7}, {'is': 7, 'Gfg': 5, 'Migliore': 2} Spiegazione : Ordinato per chiavi, in ordine crescente e inverso. Ingresso : test_dict = {Migliore: 2, per: 9, geek: 8} Produzione : {'Migliore': 2, 'Gfg': 5, 'per': 9}, {'per': 9, 'geeks': 8, 'Migliore': 2} Spiegazione : Ordinato per valori, in ordine crescente e inverso.
Caso 1: Ordina per chiavi
Questa attività viene eseguita utilizzando sorted(), in questo estraiamo le chiavi utilizzando il primo indice degli elementi del dizionario estratto da items() e lo passiamo nella chiave come funzione lambda personalizzata per essere ordinati per chiavi. Il reverse=True viene aggiunto per eseguire l'ordinamento inverso.
Python3
# 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))> |
>
>Produzione
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}>
Caso 2: Ordina per valori
Questa attività può essere eseguita in modo simile a quanto sopra, l'unica differenza è che per l'estrazione dei valori, il 2° elemento di items() viene passato come comparatore.
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))> |
>
>Produzione
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}>
Metodo n. 3: utilizzo dicollections.OrderedDict() e sorted()
Approccio
questo approccio utilizza la funzione sorted() per ordinare un dizionario in base ai suoi valori in ordine ascendente o discendente. La funzione sorted() viene chiamata con il metodo items() del dizionario e una funzione chiave che restituisce il secondo elemento di ogni tupla (cioè i valori) o la loro negazione. L'elenco di tuple risultante viene passato al costruttore OrderedDict() per creare un nuovo dizionario ordinato con le stesse coppie chiave-valore del dizionario originale ma ordinato per valore.
Algoritmo
1. Chiama la funzione sorted() sul dizionario 'test_dict', passando una funzione lambda come argomento 'chiave'.
2. La funzione lambda accetta ciascuna coppia chiave-valore come input e restituisce la chiave o il valore in base a cui ordinare, a seconda dell'ordine desiderato.
3. Utilizzare la funzione sorted() per restituire un elenco di coppie chiave-valore ordinate.
4. Passare l'elenco ordinato al costruttore OrderedDict() per creare un nuovo dizionario ordinato.
5. Restituisci il dizionario ordinato.
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))> |
>
>Produzione
OrderedDict([('Best', 2), ('Gfg', 5), ('is', 7), ('geeks', 8), ('for', 9)]) OrderedDict([('for', 9), ('geeks', 8), ('is', 7), ('Gfg', 5), ('Best', 2)])>
Complessità temporale: O(N log N), dove N è il numero di coppie chiave-valore nel dizionario.
Complessità spaziale: O(N), poiché stiamo creando un nuovo dizionario ordinato per memorizzare le coppie chiave-valore ordinate.
Metodo 4: utilizzare il metodo sorted() con una funzione lambda come parametro chiave.
Ecco i passaggi:
- Definire il dizionario da ordinare.
- Utilizza il metodo sorted() per ordinare il dizionario in base ai valori.
- Passa una funzione lambda come parametro chiave al metodo sorted() per specificare che l'ordinamento deve essere eseguito per valori.
- Utilizzare il costruttore dict() per creare un nuovo dizionario dall'elenco ordinato di tuple.
Python3
operatore resto Python
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))> |
>
>Produzione
{'Best': 2, 'Gfg': 5, 'is': 7, 'geeks': 8, 'for': 9} {'for': 9, 'geeks': 8, 'is': 7, 'Gfg': 5, 'Best': 2}>
Complessità temporale: O(n log n) dove n è il numero di elementi nel dizionario.
Spazio ausiliario: O(n) per memorizzare l'elenco ordinato di tuple. Il costruttore dict() impiega tempo O(n) per creare un nuovo dizionario dall'elenco ordinato.