Python, dado un diccionario, realiza una ordenación basada en claves o valores. [Python aplicable >=3.6v].
Entrada : test_dict = {“Gfg”: 5, “is”: 7, “Best”: 2}
Salida : {‘Best’: 2, ‘Gfg’: 5, ‘is’: 7}, {‘is’: 7, ‘Gfg’: 5, ‘Best’: 2}
Explicación : ordenados por claves, en orden ascendente e inverso.Entrada : test_dict = {“Mejor”: 2, “para”: 9, “geeks”: 8}
Salida : {‘Mejor’: 2, ‘Gfg’: 5, ‘para’: 9}, {‘para’: 9, ‘geeks’: 8, ‘Best’: 2}
Explicación : ordenados por valores, en orden ascendente e inverso.
Caso 1: Ordenar por claves
Esta tarea se realiza usando sorted(), en esto, extraemos las claves usando el primer índice de elementos del diccionario extraídos por items(), y lo pasamos en clave como función lambda personalizada para ordenar por claves. Se agrega «reverse=True» para realizar la ordenación inversa.
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))
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: Ordenar por valores
Esta tarea se puede realizar de manera similar a la anterior, la única diferencia es que para extraer valores, el segundo elemento de items() se pasa como comparador.
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}
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA