Skip to content

Sort Python Dictionary Keys Effortlessly

[

Sorting a Python Dictionary: Values, Keys, and More

Table of Contents

  • Rediscovering Dictionary Order in Python
  • Understanding What Sorting A Dictionary Really Means
  • Sorting Dictionaries in Python
    • Using the sorted() Function
    • Getting Keys, Values, or Both From a Dictionary
    • Understanding How Python Sorts Tuples
    • Using the key Parameter and Lambda Functions
    • Selecting a Nested Value With a Sort Key
    • Converting Back to a Dictionary
  • Considering Strategic and Performance Issues
    • Using Special Getter Functions to Increase Performance and Readability
    • Measuring Performance When Using itemgetter()
    • Judging Whether You Want to Use a Sorted Dictionary
    • Comparing the Performance of Different Data Structures
    • Comparing the Performance of Sorting
    • Comparing the Performance of Lookups
  • Conclusion

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.

Rediscovering Dictionary Order in Python

Before Python 3.6, dictionaries were inherently unordered. A Python dictionary is an implementation of the hash table, which is traditionally an unordered data structure.

As a side effect of the compact dictionary implementation in Python 3.6, dictionaries started to conserve insertion order. From Python 3.7, that insertion order has been guaranteed.

If you wanted to keep an ordered dictionary as a data structure, you could use collections.OrderedDict. However, since Python 3.7, dictionaries preserve insertion order by default, making collections.OrderedDict less necessary.

Understanding What Sorting A Dictionary Really Means

When you talk about sorting a dictionary, it’s important to clarify what you want to sort. Do you want to sort the keys, the values, or the key-value pairs? Sorting a dictionary by keys means ordering the keys in a specific order, while sorting by values means ordering the values in a specific order. Sorting by key-value pairs means ordering the pairs based on either the keys or the values.

Sorting Dictionaries in Python

Using the sorted() Function

In Python, you can use the built-in sorted() function to sort any iterable, including dictionaries. When you pass a dictionary to sorted(), it will return a new list with the sorted keys of the dictionary.

my_dict = {'a': 3, 'c': 1, 'b': 2}
sorted_keys = sorted(my_dict)
print(sorted_keys) # Output: ['a', 'b', 'c']

Note: The sorted() function returns a list, not a dictionary. If you want to access the sorted keys with their corresponding values, you can loop over the sorted keys and access the values using the keys.

for key in sorted_keys:
value = my_dict[key]
print(key, value)

Getting Keys, Values, or Both From a Dictionary

To sort a dictionary by values or key-value pairs, you need to extract the values or key-value pairs from the dictionary and then sort them.

To extract the values from a dictionary, you can use the values() method, which returns a view object representing the values of the dictionary. You can then convert this view object to a list and sort it.

my_dict = {'a': 3, 'c': 1, 'b': 2}
sorted_values = sorted(my_dict.values())
print(sorted_values) # Output: [1, 2, 3]

To extract the key-value pairs from a dictionary, you can use the items() method, which returns a view object representing the key-value pairs of the dictionary. You can then convert this view object to a list and sort it based on either the keys or the values.

my_dict = {'a': 3, 'c': 1, 'b': 2}
sorted_items = sorted(my_dict.items())
print(sorted_items) # Output: [('a', 3), ('b', 2), ('c', 1)]

Understanding How Python Sorts Tuples

When you sort a list of tuples, Python uses the default tuple comparison rules. It first compares the first elements of the tuples, then the second elements if the first elements are equal, and so on.

my_list = [('a', 3), ('b', 2), ('c', 1)]
sorted_list = sorted(my_list)
print(sorted_list) # Output: [('a', 3), ('b', 2), ('c', 1)]

Using the key Parameter and Lambda Functions

The sorted() function allows you to specify a key parameter, which is a function that takes an element from the iterable and returns a value that will be used for sorting. You can use this parameter to specify a custom sort order based on the keys, values, or key-value pairs of a dictionary.

my_dict = {'a': 3, 'c': 1, 'b': 2}
sorted_keys = sorted(my_dict, key=lambda k: my_dict[k])
print(sorted_keys) # Output: ['c', 'b', 'a']

Selecting a Nested Value With a Sort Key

If your dictionary contains nested values, you can use the key parameter to select a specific value to sort by. You can use dot notation or square brackets to access the nested value.

my_dict = {'a': {'x': 3}, 'c': {'x': 1}, 'b': {'x': 2}}
sorted_keys = sorted(my_dict, key=lambda k: my_dict[k]['x'])
print(sorted_keys) # Output: ['c', 'b', 'a']

Converting Back to a Dictionary

After sorting the keys, you might want to convert the sorted keys back into a dictionary. You can use a dictionary comprehension to create a new dictionary using the sorted keys.

my_dict = {'a': 3, 'c': 1, 'b': 2}
sorted_keys = sorted(my_dict)
sorted_dict = {key: my_dict[key] for key in sorted_keys}
print(sorted_dict) # Output: {'a': 3, 'b': 2, 'c': 1}

Considering Strategic and Performance Issues

When working with large dictionaries or performance-critical code, it’s important to consider the strategic and performance implications of sorting dictionaries.

Using Special Getter Functions to Increase Performance and Readability

When specifying a sort key function, you can use special getter functions like operator.itemgetter() to increase the performance and readability of your code.

import operator
my_dict = {'a': 3, 'c': 1, 'b': 2}
sorted_keys = sorted(my_dict, key=operator.itemgetter(1))
print(sorted_keys) # Output: ['c', 'b', 'a']

Measuring Performance When Using itemgetter()

To measure the performance of sorting a dictionary using operator.itemgetter(), you can use the timeit module. This module allows you to time your code and get tangible results for comparing different methods of sorting key-value data.

import operator
import timeit
my_dict = {'a': 3, 'c': 1, 'b': 2}
getter_sort = lambda: sorted(my_dict, key=operator.itemgetter(1))
regular_sort = lambda: sorted(my_dict, key=lambda k: my_dict[k])
getter_time = timeit.timeit(getter_sort, number=100000)
regular_time = timeit.timeit(regular_sort, number=100000)
print(f"Getter Sort Time: {getter_time} seconds")
print(f"Regular Sort Time: {regular_time} seconds")

Judging Whether You Want to Use a Sorted Dictionary

Sorting a dictionary can be useful in some cases, but it’s not a particularly common pattern. Consider whether you really need a sorted dictionary or if there are alternative data structures that would better suit your needs.

Comparing the Performance of Different Data Structures

When sorting key-value data, you might want to consider other data structures that could provide better performance. For example, using a list of tuples or a Pandas DataFrame might be more efficient for certain operations.

Comparing the Performance of Sorting

Sorting can be a performance-intensive operation, especially for large dictionaries. Consider the complexity and performance implications of sorting before applying it to your code.

Comparing the Performance of Lookups

In some cases, you might need to access the values of a dictionary in a specific order. If you frequently perform lookups or need to iterate through the dictionary in a custom order, maintaining a separate sorted list of keys might be more efficient.

Conclusion

In this tutorial, you learned how to sort dictionaries in Python using the sorted() function and various techniques such as using the key parameter, lambda functions, and special getter functions. You also explored strategic and performance considerations when sorting dictionaries.

Remember to consider the specific needs of your code and choose the most appropriate sorting technique and data structure for your use case. Sorting dictionaries can be powerful, but it’s important to consider the performance implications and alternative solutions if needed.

Continue practicing and experimenting with different sorting techniques to gain a deeper understanding of how to manipulate and sort dictionaries in Python.