Sorting a dictionary in Python allows you to organize its key-value pairs based on certain criteria. It includes sorting by keys or values, in ascending or descending order. Python provides several methods to achieve this. And, in this tutorial, we will explore various methods to sort a dictionary. We’ll also provide code examples and compare the methods to help you choose the most suitable one.
Different Methods to Sort a Dictionary in Python
This tutorial explains how to sort dictionaries in Python by keys or values, in ascending or descending order. Let’s explore the different ways to do this.
Method 1. Sorting a Python Dictionary by Keys
In this section, we demonstrate how to sort a dictionary based on its keys in ascending order. It sets the order alphabetically or in the default order of the keys if they are not strings (e.g., integers, dates).
Also Read: Python OrderedDict Tutorial
Sorting a dictionary by its keys is one of the basic operations. It allows you to arrange data alphabetically or in a custom order based on keys. Let’s dive into an example:
# Sample dictionary with country codes and populations country_data = {'US': 331002651, 'India': 1380004385, 'China': 1444216107, 'Brazil': 212559417} # Sort the dictionary by keys in ascending order sorted_countries = {k: country_data[k] for k in sorted(country_data)} print(sorted_countries)
The above code sorts the dictionary by keys in ascending order. It produces a new dictionary with the same data, but now alphabetically. After you run It prints the following result:
{'Brazil': 212559417, 'China': 1444216107, 'India': 1380004385, 'US': 331002651}
Let’s take another example that uses the Python lambda function along with the sorted function.
# Create a sample dictionary my_dict = {'b': 4, 'a': 2, 'd': 8, 'c': 6} # Sort the dictionary by keys sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[0])) print(sorted_dict)
This code produces the following output:
{'a': 2, 'b': 4, 'c': 6, 'd': 8}
In this example, we first convert the dictionary items into a list of tuples using items()
. Then, we use sorted()
to sort these tuples based on their first element (keys) in ascending order. Finally, we convert the sorted list of tuples back into a dictionary.
Method 2. Sort the Python Dictionary by Value
Here, we’ll show how to sort a dictionary based on its values in ascending order. The sorting arranges the dictionary items based on their values, from lowest to highest.
Sometimes, it’s more meaningful to sort a dictionary by its values. For instance, when dealing with sales data, you might want to identify the highest and lowest-performing products. Here’s an example:
# Sample dictionary with product sales data sales_data = {'Product A': 1500, 'Product B': 2800, 'Product C': 900, 'Product D': 3500} # Sort the dictionary by values in ascending order sorted_sales = {k: v for k, v in sorted(sales_data.items(), key=lambda item: item[1])} print(sorted_sales)
To make it easier for you, let’s decode the above code bit by bit.
{k: v for k, v in ...}
: This is known as dictionary comprehension. It’s a concise way to create a new dictionary based on some criteria. Let’s break it down step by step:{}
: These curly braces indicate that we’re creating a new dictionary.k: v
: This part inside the braces specifies the structure of each key-value pair in the new dictionary.k
represents the key (e.g., ‘Product A’), andv
represents the value (e.g., 1500).for k, v in ...
: This is a loop that iterates over the items in the iterable that follows. In this case, it iterates over the sorted list of key-value pairs created bysorted(sales_data.items(), key=lambda item: item[1])
.
sorted(sales_data.items(), key=lambda item: item[1])
: This part performs the sorting of thesales_data
dictionary based on the values (sales numbers) in ascending order. Here’s how it works:sales_data.items()
: This converts the dictionary into a list of key-value pairs (tuples), like('Product A', 1500)
,('Product B', 2800)
, etc.key=lambda item: item[1]
: This lambda function specifies the sorting key. It extracts the second element (item[1]
), which is the sales number, from each tuple in the list.
- Putting it all together:
- The
sorted()
function sorts the list of key-value pairs based on the sales numbers in ascending order. - The
{k: v for k, v in ...}
part creates a new dictionary where, for each pair in the sorted list,k
represents the product name (key), andv
represents the sales number (value).
- The
- Result:
- After this operation, the
sorted_sales
dictionary contains the products sorted by their sales numbers in ascending order.
- After this operation, the
When this code runs, it prints the following result:
{'Product C': 900, 'Product A': 1500, 'Product B': 2800, 'Product D': 3500}
Method 3. Sorting in Descending Order
In this section, we’ll sort a dictionary in descending order. This means we’ll reverse the order of either the keys or the values to create a descending arrangement, which is the opposite of the default ascending order.
Sorting in descending order is as simple as adding the reverse=True argument when using the sorted()
function. Here’s an example.
# Sample dictionary with product ratings ratings_data = {'Product X': 4.5, 'Product Y': 3.8, 'Product Z': 4.9, 'Product W': 4.2} # Sort the dictionary by ratings in descending order sorted_ratings = {k: v for k, v in sorted(ratings_data.items(), key=lambda item: item[1], reverse=True)} print(sorted_ratings)
Copy-paste the above code in your Python IDE. After running it, you will get the following result:
{'Product Z': 4.9, 'Product X': 4.5, 'Product W': 4.2, 'Product Y': 3.8}
In this example, we sort the dictionary by ratings in descending order to highlight the products with the highest ratings.
Method 4. Custom Python Method
Custom sorting allows you to define the criteria of your choice. In this section, we’ll explore the Python sorted() function to sort a dictionary with custom sorting keys. You can sort the dictionary based on specific attributes or criteria of the dictionary items. This method provides flexibility in sorting that goes beyond simple key or value sorting.
The sorted()
function is a versatile tool for dictionary sorting. You can customize it further by specifying different sorting criteria. Here’s an example demonstrating sorting by keys in descending order:
# Sample dictionary with city temperatures temperature_data = {'New York': 72, 'Los Angeles': 88, 'Chicago': 65, 'Miami': 92} # Step 1: Sort the dictionary by city names in descending order # Custom Sorting Key: City Names # Purpose: To arrange the cities in reverse alphabetical order based on their names. # Sorting the dictionary: sorted_cities = sorted(temperature_data.keys(), reverse=True) # Creating a new dictionary with custom sorting: sorted_temperatures = {city: temperature_data[city] for city in sorted_cities} # Step 2: Print the sorted dictionary # Finally, we print the `sorted_temperatures` dictionary, which contains the cities # sorted in descending alphabetical order. Each city name is associated with its # respective temperature. print(sorted_temperatures)
Let’s understand each step in detail:
Step 1: The code starts with a dictionary temperature_data
. It has city names as keys, and their respective temperatures as values.
Custom Sorting Key: City Names
Purpose: To arrange the cities in reverse alphabetical order based on their names.
- Sorting the Dictionary: Using the
sorted()
function withreverse=True
, we sort the city names in reverse alphabetical order. This provides us with a list of sorted city names, which acts as our custom sorting key. - Creating a New Dictionary with Custom Sorting: Next, we create a new dictionary called
sorted_temperatures
. We iterate through the sorted city names (our custom sorting key) and, for each city, associate it with its respective temperature from the originaltemperature_data
dictionary. This step creates a new dictionary with the custom sorting order.
Step 2: Finally, we print the sorted_temperatures
dictionary. It contains the cities sorted in descending alphabetical order, with each city name linked to its corresponding temperature.
As you set to run the code, the following is the output seen.
{'New York': 72, 'Miami': 92, 'Los Angeles': 88, 'Chicago': 65}
Method 5. Sorting a Dictionary In Place
If you want to sort a dictionary in place, you can use the iterkeys()
and itervalues()
methods. These methods return iterators over the keys and values in the dictionary, respectively.
To sort a dictionary in place, you can iterate over the keys or values in the dictionary and then move the key-value pairs to their desired positions.
# Define a dictionary my_dict = {'student1': 25, 'student2': 30, 'student3': 28} # Get the items of the dictionary items = list(my_dict.items()) # Sort the items by value items.sort(key=lambda item: item[1]) # Move the key-value pairs to their desired positions for i in range(len(items)): my_dict[items[i][0]] = items[i][1] # Print the sorted dictionary print(my_dict)
When you run the above code, it will print the following:
{'student1': 25, 'student2': 30, 'student3': 28}
Method 6. Sort a Nested Dictionary
A nested dictionary is a dictionary that contains other dictionaries. To sort a nested dictionary, you can use the same methods that you would use to sort a regular dictionary. However, you will need to iterate over the nested dictionaries and sort them individually.
For example, the following code sorts a nested dictionary by key:
# Define a nested dictionary my_dict = {'student1': {'age': 25, 'occupation': 'software engineer'}, 'student2': {'age': 30, 'occupation': 'data scientist'}, 'student3': {'age': 28, 'occupation': 'product manager'}} # Sort the nested dictionary by key def sort_dict_by_key(dict): keys = list(dict.keys()) keys.sort() sorted_dict = {} for key in keys: sorted_dict[key] = dict[key] return sorted_dict # Print the sorted dictionary sorted_dict = sort_dict_by_key(my_dict) print(sorted_dict)
Copy-paste the above code in your editor. When you run it, the following is the result.
{'student1': {'age': 25, 'occupation': 'software engineer'}, 'student2': {'age': 30, 'occupation': 'data scientist'}, 'student3': {'age': 28, 'occupation': 'product manager'}}
Also Read –
Python Append to a Dictionary
Python Sort Dictionary by Value With Examples
Before You Leave
In conclusion, it is important to realize that sorting dictionaries is a basic skill for any Python programmer.
Whether you’re collecting data for analysis, producing reports, or improving the user experience of your programs, sorting is the key skill.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Facebook) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.