Reputation: 23
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
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