Dado un diccionario, la tarea es obtener todos los elementos del diccionario en orden. Analicemos las diferentes formas en que podemos hacer esta tarea.
Método #1: Usarsorted()
# Python code to demonstrate # to get sorted items from dictionary # initialising _dictionary ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'} # printing iniial_dictionary print ("iniial_dictionary", str(ini_dict)) # getting items in sorted order print ("\nItems in sorted order") for key in sorted(ini_dict): print (ini_dict[key])
Producción:
iniial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'} Items in sorted order akshat bhuvan chandan
Método #2: Usar d.items()
# Python code to demonstrate # to get sorted items from dictionary # initialising _dictionary ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'} # printing iniial_dictionary print ("iniial_dictionary", str(ini_dict)) # getting items in sorted order print ("\nItems in sorted order") for key, value in sorted(ini_dict.items()): print(value)
Producción:
iniial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Items in sorted order akshat bhuvan chandan
Método #3: Usar operador
# Python code to demonstrate # to get sorted items from dictionary import operator # initialising _dictionary ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'} # printing iniial_dictionary print "iniial_dictionary", str(ini_dict) # getting items in sorted order print ("\nItems in sorted order") for key, value in sorted(ini_dict.iteritems(), key = operator.itemgetter(1), reverse = False): print key, " ", value
Producción:
iniial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'} Items in sorted order a akshat b bhuvan c chandan
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA