user3113351
user3113351

Reputation: 23

sorting a dictionary key based on values after they are converted to integers

I have a dictionary such as mydict={'tom': '100','dick': '50','harry': '121','jim':'25'}. Notice how the values are numbers in string format. i wrote a function to sort the keys based on values in descending order

def sortfunc(dict_arg):
    return sorted(dict_arg.keys(),key=dict_arg.get,reverse=True)

So my output should be ['harry','tom','dick','jim'] since 'harry' has the highest value of 121 and jim has the lowest value of 25. but i get ['dick','jim','harry','tom'] because the values are asciibetically ordered.Now i need to figure out a way to to convert the values to integers and sort the keys by the values which are converted to integers. Any hints to nudge me in the right direction are appreciated.

Upvotes: 2

Views: 767

Answers (1)

thefourtheye
thefourtheye

Reputation: 239463

You can use a lambda function here, to convert the values to int

mydict={'tom': '100','dick': '50','harry': '121','jim':'25'}
print sorted(mydict, key = lambda k: int(mydict[k]), reverse = True)

Output

['harry', 'tom', 'dick', 'jim']

Upvotes: 5

Related Questions