Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dict by highest value? [duplicate]

I've got a dict with string keys and int values. Is there any way I could take this dict and use it to get a list of the keys from highest to lowest value?

Example:

>>> myDict = {'seven': 7, 'four': 4, 'one': 1, 'two': 2, 'five': 5, 'eight': 8}
>>> myList = myDict.sortNumericallyByKeys
>>> myList
['eight', 'seven', 'five', 'four', 'two', 'one']
like image 362
Lucas Phillips Avatar asked Nov 30 '13 19:11

Lucas Phillips


People also ask

How do you sort by highest value in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

Is dict () Same as {}?

The setup is simple: the two different dictionaries - with dict() and {} - are set up with the same number of elements (x-axis). For the test, each possible combination for an update is run. In this scenario the performance also behaves similar.

How do you sort a dictionary from lowest to highest in Python?

Sort dictionary by valueitems() to the sorted() built-in function and set its sorting key keyword argument to a lambda function. We've also set the reverse=True keyword argument so that the scores are sorted in descending order from highest to lowest.


1 Answers

sorted(myDict, key=myDict.get, reverse=True)
like image 171
iruvar Avatar answered Sep 21 '22 19:09

iruvar