En Python Dictionary hay una estructura de datos bastante útil, que generalmente se usa para codificar una clave particular con valor , para que puedan recuperarse de manera eficiente.
Veamos cómo ordenar la lista alfabéticamente en un diccionario.
Ejemplo 1:
# Python program to sort the list # alphabetically in a dictionary dict ={ "L1":[87, 34, 56, 12], "L2":[23, 00, 30, 10], "L3":[1, 6, 2, 9], "L4":[40, 34, 21, 67] } print("\nBefore Sorting: ") for x in dict.items(): print(x) print("\nAfter Sorting: ") for i, j in dict.items(): sorted_dict ={i:sorted(j)} print(sorted_dict)
Producción:
Before Sorting: ('L2', [23, 0, 30, 10]) ('L3', [1, 6, 2, 9]) ('L4', [40, 34, 21, 67]) ('L1', [87, 34, 56, 12]) After Sorting: {'L2': [0, 10, 23, 30]} {'L3': [1, 2, 6, 9]} {'L4': [21, 34, 40, 67]} {'L1': [12, 34, 56, 87]}
Ejemplo #2:
# Python program to sort the list # alphabetically in a dictionary dict ={ "L1":["Geeks", "for", "Geeks"], "L2":["A", "computer", "science"], "L3":["portal", "for", "geeks"], } print("\nBefore Sorting: ") for x in dict.items(): print(x) print("\nAfter Sorting: ") for i, j in dict.items(): sorted_dict ={i:sorted(j)} print(sorted_dict)
Producción:
Before Sorting: ('L3', ['portal', 'for', 'geeks']) ('L1', ['Geeks', 'for', 'Geeks']) ('L2', ['A', 'computer', 'science']) After Sorting: {'L3': ['for', 'geeks', 'portal']} {'L1': ['Geeks', 'Geeks', 'for']} {'L2': ['A', 'computer', 'science']}
Ejemplo #3:
# Python program to sort the list # alphabetically in a dictionary dict={ "L1":[87,34,56,12], "L2":[23,00,30,10], "L3":[1,6,2,9], "L4":[40,34,21,67] } print("\nBefore Sorting: ") for x in dict.items(): print(x) sorted_dict = {i: sorted(j) for i, j in dict.items()} print("\nAfter Sorting: ", sorted_dict)
Producción:
Before Sorting: ('L1', [87, 34, 56, 12]) ('L2', [23, 0, 30, 10]) ('L3', [1, 6, 2, 9]) ('L4', [40, 34, 21, 67]) After Sorting: {'L1': [12, 34, 56, 87], 'L2': [0, 10, 23, 30], 'L3': [1, 2, 6, 9], 'L4': [21, 34, 40, 67]}
Publicación traducida automáticamente
Artículo escrito por apeksharustagi1998 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA