How to sort a dictionary in PythonPython dictionary is the collection of data which stored in the key-value form. Each key is associated with its value. It is mutable in nature, which means we can change data after its creation. It is the unordered collection of the data and allows storing duplicate values, but the key must be unique. Dictionary is declared using the curly braces {}, and the key-value pair is separated by a comma. Output: Why need to sort the dictionary
Let's understand the various ways to sort the dictionary.
Sorting By Keys and ValuesPython offers the built-in keys functions keys() and values() functions to sort the dictionary. It takes any iterable as an argument and returns the sorted list of keys. We can use the keys to sort the dictionary in the ascending order. Let's understand the following example. Example - Output: [1, 2, 3, 4, 5, 6] [(1, 'Alice'), (2, 'John'), (3, 'Andrew'), (4, 'Peter'), (5, 'Chris'), (6, 'Ruffalo')] Explanation - In the above code, we have declared a dictionary names. We used the built-in function along with the sorted() function that returned the list of the sorted keys. Next, we used the items() function to get the dictionary in the sorted order. Sorting AlgorithmThere are various sorting algorithm to sort a dictionary; we can use other arguments in the sorted method. Let's understand the following example. Example - Output: {'one': 'Monday', 'six': 'Saturday', 'three': 'Wednesday', 'two': 'Tuesday', 'five': 'Friday', 'seven': 'Sunday'} ['one', 'two', 'three', 'five', 'six', 'seven'] ['Monday', 'Tuesday', 'Wednesday', 'Friday', 'Saturday', 'Sunday'] Reverse the sorted OrderThe dictionary can be reversed using the reverse argument. Let's understand the following example. Example - Output: [6, 5, 4, 3, 2, 1] In this tutorial, we have discussed how to sort the dictionary in Python. A sorted dictionary is easy to handle the large amount of data and gives us a fast search result. Next TopicStrong Number in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India