3
I’m trying to find ways to sort a dictionary by values, then show the keys. The best way I’ve found so far is this:
import operator
def mostra_ordenado_por_valores(dic={}):
if len(dic) > 0:
for k, v in sorted(dic.items(), key=operator.itemgetter(1)): # sorts by values
print("Key:",k,"\tValue:",v)
months = {'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,
'July':31,'August':31,'September':30,'October':31,'November':30,'December':31}
mostra_ordenado_por_valores(months)
And the output is as follows:
Key: February Value: 28
Key: November Value: 30
Key: September Value: 30
Key: April Value: 30
Key: June Value: 30
Key: July Value: 31
Key: October Value: 31
Key: March Value: 31
Key: December Value: 31
Key: January Value: 31
Key: August Value: 31
Key: May Value: 31
I wonder if there’s another way to do it without using the module operator
.
You don’t want to care
operator
, that’s it?– Leonel Sanches da Silva