Python DICTionary HowTo » |
My Coding >
Programming language >
Python >
Python DICTionary HowTo
Python DICTionary HowTo (Page: 3)Go to Page: How to sort dictionary in PythonDictionary is an unsorted object and it is a common task to sort it. It is possible to imagine few different way of sorting it. Sorting by key, sorting by value and combination of sorting by key and value. Let’s consider all these cases Sorting dictionary by keyIt is possible to sort Python dictionary by its key with function sorted(). It is important to make sure that all keys are the same type in this example all keys are int
This code will also work for other compatible types of keys. As a result, two dimensional array (list of pairs key, value) will be produced Sorting dictionary by key in reversed orderIt is possible to sort in key reversed order.
Sorting dictionary by valueAnother task is to sort dictionary by it’s value. This is a bit more complicates procedure. We need to use lambda function to do this
Sorting dictionary by key and valuelambda function is a very powerful mechanism, which allow us to do any type of sorting. Now we will sort Python dictionary by its value, but for pairs with identical value, we will perform key sort as well Sorting value - key order
Sorting key - value orderThis example is senseless, because all keys are unique and sorting buy keys will be unique. This example shown only as an example of the syntax.
and this code will be equivalent to
But for key sorting it is easier to use first solution in this section.
|
Last 10 artitles
9 popular artitles
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |