Sorting means to organize the elements in a specific arrangement. No matter what kind of data a programmer is dealing with, sorting helps to organize in an efficient manner. The data can be sorted inside an array, a dictionary, a list, or a Pandas DataFrame using the sorting mechanisms. This greatly helps the user to access the data and lets them search for a specified The article discussed how a dictionary can be sorted by keys and explain it with relevant examples.
How do I sort a dictionary by key?
Before jumping onto how we can sort a dictionary by a key, let us look at what a Python dictionary is. A dictionary is a data structure that has elements in an order. The elements are present in the form of a map where each key corresponds to a certain value holding the data dictionaries that are useful for data organization and collection. No repetitive data is found in the dictionary. A Python dictionary looks like this:
dict={key_1 : value_1, key_2 : value_2,...., key_n : value_n }
A key is always a single item while its corresponding value can have multiple items of any data type. Data can be extracted from the dictionary using the key values.
Why do we need to Sort the Dictionary?
When handling the bulk data, it is useful to sort the data. Handling the bulk data when it is organized is tiresome and doing operations on the data to get our required result becomes less difficult. Sorting the data in an alphabetic or numbering eat makes the data handling really convenient.
For example, let’s suppose in an event people come to the registration desk to verify their registrations. It will be convenient to search for their names if they are alphabetically arranged instead of just going through the list every time. Likewise, sorting in the dictionary helps you deal with data efficiently.
What is the sorted() Function in Python?
The sorted sorts the elements in an iterable object like a tuple, list, or dictionary. It can sort the elements of a dictionary based on the key values. It returns an iterable object that contains the elements in a sorted manner. The syntax of the sorted function is as follows:
sorted(obj, key, reverse)
The sorted() method in Python takes the following parameters:
- obj represents the organized iterable the function returns
- The key is used for defining a custom function that can organize the iterable
- The parameter reverse has a default value of False which means that the elements will be arranged in ascending order by default. If the value of reverse is True, it means that the values will be arranged in a descending order.
A dictionary can be sorted by a key in the following ways:
- Sorting in an ascending order
- Sorting in a descending order
- Using a dictionary comprehension
- Using collections.OrderedDict Method
- Using sorted method to get the Keys in Alphabetical Order
- Using custom functions
Let us dive into each sorting method in detail:
Method 1: Sorting in an Ascending Order
The sorted function can sort the values in a Python dictionary based on key. The items() method is used to sort the dictionary based on the key values. The function returns a list of tuples that contains the sorted keys in an ascending order. As the output required is a dictionary, the dict() method is called on the converted sorted list to convert it back into the dictionary. The following code explains how a dictionary can be sorted based on keys using the sorted() and items methods in Python:
groceries = {'Frozen vegetable packets':5, 'Cereals':3, 'Cream':4, 'Mushroooms tins':7, 'Milk cartons':6}
print("The original dictionary is:\n",groceries,'\n')
res = sorted(groceries.items())
sorted_dict = dict(res)
print("The sorted dictionary in ascending order:\n",sorted_dict)
In the above code,
- A dictionary object “groceries” is defined where the grocery items are keys and their respective quantities are values.
- The dictionary groceries is printed.
- The sorted function is called on the groceries with items() method is called on it and passed as a parameter. The values in the dictionary are sorted based on the keys in an ascending order. The result is stored in the variable called result.
- The dict() method is called on Res which converts it back to the dictionary.
- The sorted dictionary is printed.
Output
The following output displays how a dictionary can be sorted in ascending order using the sorted() method in Python:
Method 2: Sorting in a Descending Order
A dictionary can be sorted in descending order by changing the reverse parameter of the sorted function to have a value of True. This will return the sorted Python dictionary in descending order. The following code explains how elements in a Python dictionary can be sorted in a descending order based on keys:
groceries = {'Frozen vegetable packets':5, 'Cereals':3, 'Cream':4, 'Mushroooms tins':7, 'Milk cartons':6}
print("The original dictionary is:\n",groceries,'\n')
res = sorted(groceries.items(), reverse=True)
sorted_dict = dict(res)
print("The sorted dictionary in ascending order:\n",sorted_dict)
In the above code,
- The groceries dictionary is printed.
- When the sorted method is called on groceries.items(), the other parameter provided is reverse=True which sorts the keys in a descending order.
- The converted list is converted back to a dictionary and printed.
Output
The elements inside the dictionary are sorted in descending order based on their key values using the sorted() function in Python:
Method 3: Using a Dictionary Comprehension
A dictionary comprehension can be used to sort the dictionary based on the key values. The keys list is sorted before using the dictionary comprehension. Using a for loop, each key is iterated in the Keys list where the sorted key is added to the sorted dictionary. The following code uses dictionary comprehension to sort the dictionary based on keys in Python:
groceries = {'Frozen vegetable packets':5, 'Cereals':3, 'Cream':4, 'Mushrooms tins':7, 'Milk cartons':6}
print("The original dictionary is:\n",groceries,'\n')
Keys = list(groceries.keys())
Keys.sort()
sorted_dict = {key: groceries[key] for key in Keys}
print("The sorted dictionary is:\n",sorted_dict)
In the above code,
- The groceries dictionary is printed.
- The list method is called on the dictionary groceries where the keys are stored in the keys list.
- Using Keys.sort(), the keys are sorted in alphabetical order.
- A variable sorted_dict defines a dictionary comprehension that iterates over each sorted key and the corresponding key-value pairs from the groceries dictionary are copied to the sorted_dict.
- The sorted dictionary is then printed.
Output
The following output displays how a dictionary can be sorted based on the key values using a dictionary comprehension in Python:
Method 4: Using collections.OrderedDict Method
The OrderedDict method from the collections class. The sorted method sorts the elements of the dictionary and the OrderedDict method is called on the dictionary to return the sorted dictionary. The OrderedDict helps to maintain the order of the dictionary’s elements and sort them based on keys. The following code explains how collections.OrderedDict Method can sort the dictionary based on keys in Python:
from collections import OrderedDict
groceries = {'Frozen vegetable packets':5, 'Cereals':3, 'Cream':4, 'Mushrooms tins':7, 'Milk cartons':6}
print("The original dictionary is:\n",groceries,'\n')
sorted_dict = OrderedDict(sorted(groceries.items()))
print("The sorted dictionary is:\n",sorted_dict)
In the above code,
- The OrderedDict class from the module collections is imported.
- The dictionary groceries is printed.
- The sorted function is called on groceries.items() which sorts the dictionary based on the keys. The OrderedDict is called on the sorted list and the result is stored in the variable sorted_dict.
- The sorted dictionary is printed.
Output
The following output displays how to use the collections.OrderedDict class along with the sorted method can sort the dictionary based on the keys in Python:
Method 5: Using the sorted Method to get the Keys in Alphabetical Order
The sorted() method by default returns elements in alphabetical order. The following code uses the sorted() method to sort the dictionary by key in alphabetical order in Python:
groceries = {'Frozen vegetable packets':5, 'Cereals':3, 'cream':4, 'Mushrooms tins':7, 'Milk cartons':6, 'olives tin':1}
print("The original dictionary is:\n",groceries,'\n')
sorted_dict = sorted(groceries)
print("The sorted dictionary is:\n",sorted_dict)
In the above code,
- The groceries dictionary is printed.
- The sorted method is called on groceries and the result is stored in the variable sorted_dict.
- The sorted dictionary is printed.
Output
The following output displays how a dictionary can be sorted based on keys using the sorted() method in Python:
Method 6: Using Custom Functions
A custom Lambda function can be used to sort a dictionary by key. The key parameter can define a Lambda expression that can sort the dictionary items based on keys. The following code uses a custom Lambda expression to sort the dictionary based on keys in Python:
groceries = {'Frozen vegetable packets':5, 'Cereals':3, 'cream':4, 'Mushrooms tins':7, 'Milk cartons':6, 'olives tin':1}
print("The original dictionary is:\n",groceries,'\n')
sorted_dict = dict(sorted(groceries.items(), key=lambda item: item[0]))
print("The sorted dictionary is:\n",sorted_dict)
In the above code,
- The dictionary groceries is printed.
- The sorted function is called on groceries to sort the dictionary based on keys.
- The key parameter equates to a Lambda expression that gets the first element of each tuple which in this case is the value of key.
- The sorted list is converted back to the dictionary using the dict method.
Output
The following output displays the sorted dictionary using a Lambda expression to extract the keys:
Conclusion
A Python dictionary can be sorted based on keys using the sorted() method which returns an iterable containing the sorted items. The dictionary can be sorted in ascending and descending order. This is helpful in data analysis and when certain data needs to be accessed. Arranging the elements in a dictionary makes it convenient to search for specified data present. This is helpful in many applications like tracking, investigation, and more. The article discusses different methods of sorting a dictionary based on keys and explains each method with its relevant example.