python-3.x – Show the contents of a dictionary in sorted mode according to values

Question:

I'm trying to find ways to sort a dictionary by values ​​and then display the keys. The best way I've found so far is as follows:

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 would like to know if there is another way to do this without using the operator module.

Answer:

You can use an OrderedDict.

from collections import OrderedDict
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}
months_ordered = OrderedDict(sorted(months.items(), key=lambda t: t[1]))

for k, v in months_ordered.items():
    print('Key: {0} \t Value: {1}'.format(k,v))
Scroll to Top