In this article, we are going to see dict sort in Python i.e. how can we sort a dictionary in Python. We will see all the methods with examples and will do deep into all the methods for better understanding. But before that, let’s see a brief introduction to Dictionary in Python. Click here to jump directly to sorting a dictionary in Python
Dictionary in Python
In Python, the dictionary is used to store multiple key-value pairs. Each item has a key
and a corresponding value that is expressed as a pair of Key-Value pairs. Keys are used to accessing a certain value of a dictionary. In order to define a dictionary in Python, we use curly braces {}. Inside curly braces, we have to put our key values pair.
my_dictionary = {"Bat": "Ball", "Car": "Bike"}
Here “Bat” is the key to “Ball” and “Car” is the key to value “Bike”.
Dictionary items are ordered, changeable, and do not allow duplicates. Key and value inside the dictionary can be of any valid data type or collection in python. Dictionary items can be a tuple or dictionary itself let us see an example to understand this:-
my_dictionary = {"Bat": "Ball", "tuple": (1, 2, 3, 4)}
As in the example above, the second item of this dictionary is a tuple.
my_dictionary = {"Bat": "Ball", "dictionary": {"Name": "Williams", "age": 56}}
In this example above, the second element is the dictionary itself.
So, In this way python provides us good flexibility that while using a dictionary we can use another data structure (collection type) inside our dictionary.
Sorting a Dictionary in Python
The word ‘sorting’ means arranging the data. So, sorting a dictionary means arranging the items of the dictionary in a certain order.
For sorting a dictionary in python we just have to use the sorted() function and this function is a built-in function in python. In a simple language, this function takes a dictionary as input and gave us a sorted dictionary as an output. Let us now take a close look at this function and study in deep about this function. You are seeing Dict Sort in Python.
sorted() function
The sorted() function is also used to sort strings, tuples, lists, and sets. So this single function can be used to sort all the types of collections in python.
Syntax of sorted() Function
sorted( iterable , key, reverse)
sorted() function parameters
This sorted() function maximum takes 3 parameters, these parameters are described below:-
- iterable:- The item that has to be sorted like string, list, tuple, set or dictionary, or any other iterator. So, as the first parameter, we need to pass an unsorted dictionary. This is a required parameter, if it is not passed when we call our sorted() function then it will throw an error.
- key:- This is an optional parameter. If this is not passed while calling out the sorted() function, then our program will run without any error. A function that serves as a key for the sort comparison has to be passed as a parameter. This would get clear when we take an example. By default value of this parameter is none, if no value has been passed during the function call. You are reading Dict Sort in Python.
- reverse:- This takes Boolean as a parameter. If true is passed when the function is called then the sorted output will be in reverse order (or in descending order). By default, the value of this parameter is false, if no value has been passed during the function call. This is also an optional parameter, if it is not passed during the function call, our program will run without any error.
This function always returns a list as an output no matter what type of iterable has been passed. If we have passed an unsorted dictionary as an input it always gives us a sorted list as an output.
Sorting Keys of a dictionary in Python
# Initializing an empty dictionary
my_dictionary = {}
# Add key value pair in our dictionary
my_dictionary[109] = "Andrew"
my_dictionary[25] = "James"
my_dictionary[33] = "Smith"
my_dictionary[66] = "Samsung"
my_dictionary[19] = "Games"
for i in sorted(my_dictionary.keys()):
print(i, end=" ")
Output:
19 25 33 66 109
For sorting out all the keys in ascending order we have to use the sorted function and for printing all the values we have used for the loop, inside the sorted function we have passed dictionary.keys() where keys() is a built-in function that is used to access all the values of a dictionary. You are seeing Dict Sort in Python.
Sorting Values of a dictionary in Python
For sorting the values of a dictionary the logic and code are almost the same the only difference is that we have to pass dictionary.values() in place of the dictionary.keys() as a parameter inside the sorted function.
Let’s see an example of sorting a dictionary in python with this method.
# Initializing an empty dictionary
my_dictionary = {}
# Add key value pair in our dictionary
my_dictionary[109] = "Andrew"
my_dictionary[25] = "James"
my_dictionary[33] = "Smith"
my_dictionary[66] = "Samsung"
my_dictionary[19] = "Games"
for i in sorted(my_dictionary.values()):
print(i, end=" ")
Output:
Andrew Games James Samsung Smith
For sorting out all the values in alphabetical order we have to use the sorted function again. Inside the sorted function we have passed dictionary.values() where values() is also a built-in function that is used to access all the values of a dictionary. You are reading Dict Sort in Python.
Sorting the Keys in alphabetical
We will now study how to sort keys and their corresponding values together in alphabetical order. To do so, we have to pass dictionary.items() inside the sorted() function as a parameter where items() is also a built n function that is used to access all the keys and their corresponding values together, and hence sorted function will sort them together.
Let’s see an example of sorting a dictionary in python with this method.
# initializing an empty dictionary
my_dictionary = {}
# Add key value pair in our dictionary
my_dictionary["Warner"] = "Andrew"
my_dictionary["Mix"] = "James"
my_dictionary["Aviral"] = "Smith"
my_dictionary["Python"] = "Samsung"
my_dictionary["Java"] = "Games"
for i in sorted(my_dictionary.items()):
print(i, end=" ")
Output:
Aviral', 'Smith') ('Java', 'Games') ('Mix', 'James') ('Python', 'Samsung')
('Warner', 'Andrew')
For sorting out all the keys in alphabetical order we have to use the sorted function and for printing all the values we have used for the loop, inside the sorted function we have passed dictionary.items() where items() is also a built-in function that is used to access all the key-value pair of a dictionary.
Reverse Parameter in sorted() function
To sort dictionary keys or values in reverse order, just pass reverse = True in the sorted function as the 2nd parameter.
Sorting the Keys of a Dictionary in Reverse Order:-
Let’s understand an example of sorting a dictionary in python with this method.
# Initializing an empty dictionary
my_dictionary= {}
# Add key value pair in our dictionary
my_dictionary[109] = "Andrew"
my_dictionary[25] = "James"
my_dictionary[33] = "Smith"
my_dictionary[66] = "Samsung"
my_dictionary[19] = "Games"
for i in sorted(my_dictionary.keys(), reverse = True):
print(i, end=" ")
Output:
109 66 33 25 19
Sorting the Values of Dictionary in Reverse Order:-
Let’s see an example of sorting a dictionary with this method.
# Initializing an empty dictionary
my_dictionary = {}
# Add key value pair in our dictionary
my_dictionary[109] = "Andrew"
my_dictionary[25] = "James"
my_dictionary[33] = "Smith"
my_dictionary[66] = "Samsung"
my_dictionary[19] = "Games"
for i in sorted(my_dictionary.values(), reverse = True):
print(i, end=" ")
Output:
Smith Samsung James Games Andrew
Key Parameter in sorted() function
Key can be passed as the 3rd parameter of the sorted() function. Key takes a function or lambda function (function with no name) as an assigned value. Let’s see an example of sorting a dictionary in python with this method.
# Initializing an empty dictionary
my_dictionary = {}
my_dictionary["Warner"] = "Andrew"
my_dictionary["Mix"] = "James"
my_dictionary["Adams"] = "Smith"
my_dictionary["Python"] = "Samsung"
my_dictionary["Java"] = "Games"
for i in sorted(my_dictionary.values(), key = lambda item: item[1]):
print(i, end=" ")
Output:
James Samsung Games Smith Andrew
Here, a key parameter has been passed and its value is a lambda function, and this function will apply to each element of the dictionary. Here, this lambda function wants to make every element move to index position 1. So, every element will move to index 1 and the element which is already at index 1 will move to the next index and that’s why we have got this output. You are seeing Dict Sort in Python.
Need For Sorting a Dictionary in Python
We need sorting of data in the dictionary to reduce the time complexity of data for processing. If the dictionary is sorted it will take less time for processing in comparison to an unsorted dictionary. Therefore sorting is very important especially when we have to deal with a large amount of data. So, we successfully completed Dict Sort in Python.
Sorting a dictionary basically means arranging its keys or values in alphabetical order if their data type is String or in ascending order if their data type is an integer.
We hope this article on Dict Sort in Python helps you.
Thank you for reading this article, click here to start learning Python in 2022.
Also Read:
- What is web development for beginners?
- What does if __name__ == __main__ do in Python?
- Python | CRUD operations in MongoDB
- Create your own ChatGPT with Python
- Bakery Management System in Python | Class 12 Project
- SQLite | CRUD Operations in Python
- Event Management System Project in Python
- Ticket Booking and Management in Python
- Hostel Management System Project in Python
- Sales Management System Project in Python
- Bank Management System Project in C++
- Python Download File from URL | 4 Methods
- Python Programming Examples | Fundamental Programs in Python
- Spell Checker in Python
- Portfolio Management System in Python
- Stickman Game in Python
- Contact Book project in Python
- Loan Management System Project in Python
- Cab Booking System in Python
- Brick Breaker Game in Python
- Tank game in Python
- GUI Piano in Python
- Ludo Game in Python
- Rock Paper Scissors Game in Python
- Snake and Ladder Game in Python
- Puzzle Game in Python
- Medical Store Management System Project in Python
- Creating Dino Game in Python
- Tic Tac Toe Game in Python
- Test Typing Speed using Python App