Display contents of a dictionary in sorted mode according to values

Asked

Viewed 843 times

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.

2 answers

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

0

You can use a Construct called lambda to create an anonymous function:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.