Show dictionary contents in sorted order according to values

Posted on

Question :

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

months = {'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,


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 a construct named lambda to create an anonymous function:

sorted(months.items(), key=lambda x: x[1])


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))


Leave a Reply

Your email address will not be published. Required fields are marked *