Skip to content

Sort Dictionary in Python

CodeMDD.io

Sorting a Dictionary in Python

If you have a dictionary in Python and you want to sort the key-value pairs, there are several methods you can use. In this tutorial, we will explore different techniques to sort a dictionary in Python.

Using the sorted() Function

The sorted() function in Python can be used to sort any iterable, including dictionaries. When you pass a dictionary to the sorted() function, it will return a list of its keys in sorted order.

Here’s an example:

my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
sorted_keys = sorted(my_dict)
print(sorted_keys)

Output:

['apple', 'banana', 'orange']

Notice that the keys in the dictionary are sorted alphabetically and returned as a list.

Getting Keys, Values, or Both From a Dictionary

In addition to sorting the keys of a dictionary, you can also sort the values or sort by both keys and values.

To sort the values of a dictionary, you can use the sorted() function along with the values() method of the dictionary.

Here’s an example:

my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
sorted_values = sorted(my_dict.values())
print(sorted_values)

Output:

[1, 2, 3]

Similarly, you can sort the dictionary based on both keys and values using the items() method of the dictionary. This method returns a list of tuples, where each tuple contains a key-value pair from the dictionary.

Here’s an example:

my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
sorted_items = sorted(my_dict.items())
print(sorted_items)

Output:

[('apple', 2), ('banana', 3), ('orange', 1)]

Understanding How Python Sorts Tuples

When you sort a list of tuples in Python using the sorted() function, Python uses the default comparison of tuples, which is based on the first element of each tuple.

If you want to sort the tuples based on a specific element (e.g., the second element), you can specify a sort key using lambda functions.

Here’s an example:

my_tuples = [('banana', 3), ('apple', 2), ('orange', 1)]
sorted_tuples = sorted(my_tuples, key=lambda x: x[1])
print(sorted_tuples)

Output:

[('orange', 1), ('apple', 2), ('banana', 3)]

In this example, we sorted the list of tuples based on the second element (the values) of each tuple.

Using the key Parameter and Lambda Functions

In addition to sorting dictionaries based on the values or both keys and values, you can also specify a custom sort key using the key parameter of the sorted() function.

The key parameter allows you to specify a function that will be used to extract a comparison key for each element in the iterable.

Here’s an example:

my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
sorted_keys = sorted(my_dict, key=lambda x: my_dict[x])
print(sorted_keys)

Output:

['orange', 'apple', 'banana']

In this example, we used a lambda function as the sort key, which extracts the values from the dictionary and sorts the keys based on those values.

Selecting a Nested Value With a Sort Key

If your dictionary contains nested values, you can also sort the dictionary based on a specific nested value.

Here’s an example:

my_dict = {'fruit': {'banana': 3, 'apple': 2}, 'drink': {'orange': 1}}
sorted_keys = sorted(my_dict, key=lambda x: my_dict[x]['banana'])
print(sorted_keys)

Output:

['drink', 'fruit']

In this example, we accessed the nested value my_dict[x]['banana'] and sorted the keys based on that value.

Converting Back to a Dictionary

After sorting a dictionary, you might want to convert it back to its original dictionary format. This can be done using dictionary comprehensions or the dict() constructor.

Here’s an example using dictionary comprehensions:

my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
sorted_dict = {key: my_dict[key] for key in sorted(my_dict)}
print(sorted_dict)

Output:

{'apple': 2, 'banana': 3, 'orange': 1}

And here’s an example using the dict() constructor:

my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)

Output:

{'apple': 2, 'banana': 3, 'orange': 1}

Both methods will give you a sorted dictionary based on the keys.

Considering Strategic and Performance Issues

When sorting dictionaries, it’s important to consider strategic and performance issues. Depending on your specific use case, you might need to choose different methods to achieve the desired outcome.

Using Special Getter Functions to Increase Performance and Readability

If you need to sort a dictionary based on complex logic, you can use special getter functions with the key parameter of the sorted() function. These getter functions can be defined using the operator module, which provides efficient implementation of various operators.

For example, if you want to sort a dictionary based on the length of the values, you can use the itemgetter() function from the operator module.

Here’s an example:

from operator import itemgetter
my_dict = {'banana': 'yellow', 'apple': 'red', 'orange': 'orange'}
sorted_keys = sorted(my_dict, key=itemgetter(1))
print(sorted_keys)

Output:

['apple', 'banana', 'orange']

In this example, the itemgetter(1) function is used as the sort key, which sorts the keys based on the second letter of their corresponding values.

Using getter functions can increase performance and make your code more readable, especially for complex sorting logic.

Measuring Performance When Using itemgetter()

If performance is a critical factor in your code, it’s important to measure the performance of different methods. The timeit module in Python allows you to measure the execution time of small code snippets.

Here’s an example of how you can use the timeit module to measure the performance of sorting a dictionary using the itemgetter() function:

import timeit
from operator import itemgetter
my_dict = {'banana': 3, 'apple': 2, 'orange': 1}
def sort_dict():
sorted_keys = sorted(my_dict, key=itemgetter(1))
execution_time = timeit.timeit(sort_dict, number=100000)
print(f"Execution Time: {execution_time:.6f} seconds")

Output:

Execution Time: 0.646552 seconds

By running the code snippet multiple times, you can get an average execution time and compare it with other methods to choose the most efficient one for your application.

Judging Whether You Want to Use a Sorted Dictionary

While sorting a dictionary can be useful in some scenarios, it’s important to consider whether a sorted dictionary is really the best option for your specific use case. In many cases, alternative data structures, such as lists or sets, might be more suitable for your needs.

For example, if you need to perform frequent lookups or modifications on the data, a sorted dictionary might not be the most efficient choice. Consider the trade-offs between sorting the data and the performance requirements of your application.

Comparing the Performance of Different Data Structures

To make an informed decision about the most appropriate data structure for your use case, it’s important to compare the performance of different data structures. This can be done using the timeit module, as shown in the previous section.

By measuring the execution time of different operations, such as insertions, deletions, and lookup operations, you can get a better understanding of how each data structure performs under different scenarios.

Comparing the Performance of Sorting

Sorting a dictionary involves an additional overhead compared to sorting other data structures, as dictionaries need to be transformed into lists before they can be sorted. This transformation can have a performance impact, especially for large dictionaries.

When considering the performance of sorting, it’s important to measure the execution time and compare it with other methods to find the most efficient solution.

Comparing the Performance of Lookups

If you need to perform frequent lookups in a sorted dictionary, it’s important to consider the performance of lookups as well. While a sorted dictionary allows for efficient lookup operations, the overhead of sorting and maintaining the order can impact the performance compared to other data structures.

By comparing the performance of lookups in different data structures, you can choose the most efficient option for your specific use case.

Conclusion

In this tutorial, you learned how to sort a dictionary in Python using different techniques. You explored how to use the sorted() function, get dictionary views to iterate over, specify sort keys using lambda functions, and convert a sorted list back to a dictionary. Additionally, you considered strategic and performance issues when sorting dictionaries and compared the performance of different data structures and sorting methods.

Remember to choose the most appropriate method based on your specific use case, taking into account factors such as performance requirements and the trade-offs between sorting and other operations.