Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to sort a dictionary in Python

Introduction

Sorting a dictionary in Python is a common task you might encounter while programming. A dictionary is a built-in Python data structure that stores key-value pairs. It is an unordered collection, which means that the elements in a dictionary have no specific order. In this blog post, we will explore different ways to sort a dictionary, focusing on sorting by keys and sorting by values. We will also look at some common use cases and examples to make it easy for someone who is learning programming. So, let's dive into it!

What is a Dictionary?

To understand how to sort a dictionary in Python, first, we need to understand what a dictionary is. A dictionary is a collection of key-value pairs, where each key is mapped to a value. It is similar to a real-life dictionary, where words (keys) are associated with their meanings (values).

In Python, dictionaries are created using curly braces {} or the dict() constructor. Here's an example of a dictionary:

my_dict = {'apple': 4, 'banana': 3, 'orange': 5}

In this example, the keys are fruit names, and the values are their respective quantities. Keep in mind that the keys in a dictionary must be unique, while the values can be repeated.

Sorting a Dictionary by Keys

Now that we have a basic understanding of dictionaries, let's learn how to sort them by keys. Since dictionaries are unordered, we cannot directly sort them. However, we can convert them to a different data structure, such as a list of tuples, and then sort that list.

Here's a step-by-step approach to sort a dictionary by its keys:

Step 1: Convert the Dictionary to a List of Tuples

To sort a dictionary by its keys, we first need to convert it into a list of tuples, where each tuple contains a key-value pair. We can achieve this using the items() method of the dictionary:

my_dict = {'apple': 4, 'banana': 3, 'orange': 5}
list_of_tuples = list(my_dict.items())
print(list_of_tuples)

Output:

[('apple', 4), ('banana', 3), ('orange', 5)]

Step 2: Sort the List of Tuples

Next, we need to sort the list of tuples based on the keys (the first element in each tuple). We can use the sorted() function, which returns a new sorted list without modifying the original list:

sorted_list = sorted(list_of_tuples)
print(sorted_list)

Output:

[('apple', 4), ('banana', 3), ('orange', 5)]

Step 3: Convert the Sorted List of Tuples back to a Dictionary

Finally, we can convert the sorted list of tuples back to a dictionary using a dictionary comprehension:

sorted_dict = {key: value for key, value in sorted_list}
print(sorted_dict)

Output:

{'apple': 4, 'banana': 3, 'orange': 5}

Putting It All Together

Here's the complete code to sort a dictionary by its keys:

my_dict = {'apple': 4, 'banana': 3, 'orange': 5}

# Convert the dictionary to a list of tuples
list_of_tuples = list(my_dict.items())

# Sort the list of tuples
sorted_list = sorted(list_of_tuples)

# Convert the sorted list of tuples back to a dictionary
sorted_dict = {key: value for key, value in sorted_list}

print(sorted_dict)

Output:

{'apple': 4, 'banana': 3, 'orange': 5}

Sorting a Dictionary by Values

Sometimes you might want to sort a dictionary by its values instead of its keys. While the process is similar to sorting by keys, there are a few differences. Let's go through the steps to sort a dictionary by its values:

Step 1: Convert the Dictionary to a List of Tuples

Just like in the previous example, we first need to convert the dictionary to a list of tuples:

my_dict = {'apple': 4, 'banana': 3, 'orange': 5}
list_of_tuples = list(my_dict.items())
print(list_of_tuples)

Output:

[('apple', 4), ('banana', 3), ('orange', 5)]

Step 2: Sort the List of Tuples by Values

Now, instead of sorting the list of tuples by keys, we want to sort it by values (the second element in each tuple). We can use the sorted() function again, but this time, we need to specify a key argument that tells the function to sort the list based on the values:

sorted_list = sorted(list_of_tuples, key=lambda x: x[1])
print(sorted_list)

Output:

[('banana', 3), ('apple', 4), ('orange', 5)]

In this example, we used a lambda function as the key argument. A lambda function is a small, anonymous function that can be used for simple operations. In this case, it takes a tuple x as input and returns the second element of the tuple (x[1]).

Step 3: Convert the Sorted List of Tuples back to a Dictionary

Finally, we convert the sorted list of tuples back to a dictionary using a dictionary comprehension:

sorted_dict = {key: value for key, value in sorted_list}
print(sorted_dict)

Output:

{'banana': 3, 'apple': 4, 'orange': 5}

Putting It All Together

Here's the complete code to sort a dictionary by its values:

my_dict = {'apple': 4, 'banana': 3, 'orange': 5}

# Convert the dictionary to a list of tuples
list_of_tuples = list(my_dict.items())

# Sort the list of tuples by values
sorted_list = sorted(list_of_tuples, key=lambda x: x[1])

# Convert the sorted list of tuples back to a dictionary
sorted_dict = {key: value for key, value in sorted_list}

print(sorted_dict)

Output:

{'banana': 3, 'apple': 4, 'orange': 5}

Conclusion

In this blog post, we learned how to sort a dictionary in Python by its keys and values. We explored the process of converting a dictionary to a list of tuples, sorting the list based on keys or values, and converting the sorted list back to a dictionary. We also looked at some code examples to help you better understand the concept.

Remember that sorting a dictionary might not always be necessary, as dictionaries are unordered by nature. However, knowing how to sort dictionaries can be useful in certain situations, such as when you need to display the contents of a dictionary in a specific order.

I hope this blog post has helped you understand how to sort dictionaries in Python. Keep practicing and happy coding!