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']
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.
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.
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.
sorted(myDict, key=myDict.get, reverse=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With