Skip to content

Effortlessly Sort Python Dict Keys

[

Sorting a Python Dictionary: Values, Keys, and More

by Ian Currie

You’ve got a dictionary, but you’d like to sort the key-value pairs. Perhaps you’ve tried passing a dictionary to the sorted() function but haven’t gotten the results you expected. In this tutorial, you’ll go over everything you need to know if you want to sort dictionaries in Python.

Getting Started

To get started, make sure you have a basic understanding of dictionaries, lists, tuples, and functions. With this knowledge, you’ll be able to sort dictionaries by the end of this tutorial. Some familiarity with lambda functions and higher-order functions will also be helpful.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries in Python were inherently unordered. They were implemented as hash tables, which traditionally do not preserve insertion order. However, starting from Python 3.6, dictionaries began to preserve the insertion order as a side effect of the compact dictionary implementation. Since Python 3.7, the insertion order in dictionaries has been guaranteed.

Sorting Dictionaries in Python

There are several ways to sort dictionaries in Python:

  1. Using the sorted() Function: The sorted() function can be used to sort a dictionary based on its keys or values. By default, it sorts based on the keys.
my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items())
print(sorted_dict)
  1. Getting Keys, Values, or Both From a Dictionary: You can use the keys(), values(), or items() methods of a dictionary to get a view object, which can then be sorted.
my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_keys = sorted(my_dict.keys())
sorted_values = sorted(my_dict.values())
print(sorted_keys)
print(sorted_values)
  1. Understanding How Python Sorts Tuples: When sorting a dictionary using sorted(), Python compares the tuples of key-value pairs. By default, it compares the keys first and then the values.

  2. Using the key Parameter and Lambda Functions: The key parameter of the sorted() function allows you to specify a function that will be used to extract a comparison key from each element before sorting.

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])
print(sorted_dict)
  1. Selecting a Nested Value with a Sort Key: If your dictionary contains nested structures, you can use a sort key function to select a specific value for sorting.

  2. Converting Back to a Dictionary: After sorting a dictionary, you can convert it back to a dictionary using the dict() constructor or dictionary comprehensions.

Strategic and Performance Considerations

When sorting dictionaries, you should consider both strategic and performance issues:

  1. Using Special Getter Functions to Increase Performance and Readability: Instead of using lambda functions, you can create special getter functions using itemgetter(), which can improve performance and readability.

  2. Measuring Performance When Using itemgetter(): You can compare the performance of different getter functions using the timeit module to determine the most efficient approach.

  3. Judging Whether You Want to Use a Sorted Dictionary: Sorting a dictionary is not a common pattern, so you should consider whether a sorted dictionary is really necessary for your use case.

  4. Comparing the Performance of Different Data Structures: Depending on your specific use case, you might want to consider using alternative data structures to improve performance.

  5. Comparing the Performance of Sorting: Sorting a dictionary can be an expensive operation, especially for large dictionaries. You should be aware of the performance implications when sorting.

  6. Comparing the Performance of Lookups: Depending on the data structure you choose, the performance of lookups can vary. Consider the trade-offs between sorting and lookups in your application.

Conclusion

Sorting dictionaries in Python can be done using various techniques such as the sorted() function, dictionary views, lambda functions, and sort key selection. However, sorting dictionaries is not a common pattern, and you should carefully consider the strategic and performance implications before deciding to use a sorted dictionary.