Skip to content

Sort Dictionary in Python Effortlessly

CodeMDD.io

Sorting a Python Dictionary: Values, Keys, and More

If you have a dictionary in Python and you want to sort the key-value pairs, this tutorial will guide you through the process. Whether you are using the sorted() function or want to specify a sort key, this article will provide you with the necessary information. Let’s dive into sorting dictionaries in Python!

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries in Python were inherently unordered. They were implemented as hash tables, which traditionally don’t maintain a specific order. However, starting from Python 3.6, dictionaries began to preserve insertion order as a side effect of the compact dictionary implementation. Since Python 3.7, the insertion order is guaranteed.

Understanding What Sorting A Dictionary Really Means

When we talk about sorting a dictionary, what we mean is sorting the key-value pairs based on certain criteria. The key-value pairs can be sorted by either the keys or the values, depending on your needs.

Sorting Dictionaries in Python

Using the sorted() Function

The simplest way to sort a dictionary is to use the sorted() function. This function takes an iterable, such as a dictionary, and returns a new list containing the sorted elements. To achieve this, the sorted() function uses the default comparison behavior of the keys.

my_dict = {"apple": 3, "banana": 2, "cherry": 4}
sorted_dict = sorted(my_dict)
print(sorted_dict)

Output:

['apple', 'banana', 'cherry']

Getting Keys, Values, or Both From a Dictionary

If you want to sort based on values or both keys and values, you need to access the keys or values separately. You can do this by using the keys(), values(), or items() methods of the dictionary.

my_dict = {"apple": 3, "banana": 2, "cherry": 4}
sorted_keys = sorted(my_dict.keys())
sorted_values = sorted(my_dict.values())
sorted_items = sorted(my_dict.items())
print(sorted_keys)
print(sorted_values)
print(sorted_items)

Output:

['apple', 'banana', 'cherry']
[2, 3, 4]
[('apple', 3), ('banana', 2), ('cherry', 4)]

Understanding How Python Sorts Tuples

When sorting dictionaries, you may encounter a situation where the values are the same for multiple key-value pairs. In such cases, Python will sort these key-value pairs based on the key itself.

my_dict = {"apple": 3, "banana": 2, "cherry": 3}
sorted_items = sorted(my_dict.items())
print(sorted_items)

Output:

[('apple', 3), ('cherry', 3), ('banana', 2)]

Using the key Parameter and Lambda Functions

The sorted() function allows you to specify a custom sort key using the key parameter. This parameter expects a callable that will be used to extract a value for comparison.

my_dict = {"apple": 3, "banana": 2, "cherry": 4}
sorted_values = sorted(my_dict.items(), key=lambda x: x[1])
print(sorted_values)

Output:

[('banana', 2), ('apple', 3), ('cherry', 4)]

Selecting a Nested Value With a Sort Key

If you have a nested structure within your dictionary and want to sort based on a nested value, you can use a more complex lambda function as the sort key.

my_dict = {"apple": {"price": 3}, "banana": {"price": 2}, "cherry": {"price": 4}}
sorted_values = sorted(my_dict.items(), key=lambda x: x[1]["price"])
print(sorted_values)

Output:

[('banana', {'price': 2}), ('apple', {'price': 3}), ('cherry', {'price': 4})]

Converting Back to a Dictionary

After sorting the key-value pairs, if you want to convert the result back into a dictionary, you can use the dict() constructor.

my_dict = {"apple": 3, "banana": 2, "cherry": 4}
sorted_items = sorted(my_dict.items())
sorted_dict = dict(sorted_items)
print(sorted_dict)

Output:

{'apple': 3, 'banana': 2, 'cherry': 4}

Considering Strategic and Performance Issues

In certain cases, sorting dictionaries may have strategic and performance implications. It is important to consider these factors when deciding whether to use a sorted dictionary.

Using Special Getter Functions to Increase Performance and Readability

If your primary concern is performance, you can use special getter functions such as itemgetter() to improve performance and readability.

Measuring Performance When Using itemgetter()

To compare the performance of different approaches, you can use the timeit module to measure the execution time of your code.

Judging Whether You Want to Use a Sorted Dictionary

Sorting dictionaries is not a common use case because dictionaries are designed for fast access based on keys rather than sorted access.

Comparing the Performance of Different Data Structures

It’s also worth considering alternative data structures, such as lists or tuples, if you frequently need sorted access to your data.

Comparing the Performance of Sorting

When dealing with large datasets, the performance of the sorting algorithm itself becomes crucial. Python’s built-in sorting algorithms ensure good performance in most cases.

Comparing the Performance of Lookups

If you frequently need to access individual items within a sorted collection, you should consider the performance of lookups as well.

Conclusion

Sorting a dictionary in Python involves using the sorted() function and understanding the behavior of specific parameters, such as the key parameter. By following this tutorial, you have learned various techniques to sort dictionaries in Python based on keys, values, or even nested attributes. Additionally, you’ve explored alternative data structures and considered performance implications. With this knowledge, you can effectively sort dictionaries in your Python programs.

CodeMDD.io