Skip to content

Effortlessly Sort Python Dictionary by Key

[

Sorting a Python Dictionary by Key

In this tutorial, you will learn how to sort a Python dictionary by key. You may have a dictionary that you want to order based on its keys in ascending or descending order. Sorting a dictionary by key can be useful when you want to perform operations on the dictionary in a specific order or when you want to display the dictionary’s contents in a sorted manner.

Using the sorted() Function

One way to sort a dictionary by key is to use the sorted() function. The sorted() function takes an iterable, such as a dictionary, and returns a new list containing the elements in sorted order.

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items())

In the code above, my_dict.items() returns a list of tuples, where each tuple consists of a key-value pair from the dictionary. The sorted() function then sorts the list of tuples based on the keys, resulting in a sorted list of tuples. Finally, the sorted list can be converted back into a dictionary if needed.

Preserving the Original Dictionary Order

If you want to keep the original ordering of the dictionary while still having a sorted version, you can use the collections.OrderedDict class. This class remembers the order in which the keys were added to the dictionary.

from collections import OrderedDict
my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = OrderedDict(sorted(my_dict.items()))

In the code above, sorted() is used to sort the dictionary items and then OrderedDict() is used to convert the sorted list of tuples back into an ordered dictionary.

Sorting in Descending Order

By default, the sorted() function sorts elements in ascending order. If you want to sort a dictionary by key in descending order, you can pass the reverse=True argument to the sorted() function.

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict = sorted(my_dict.items(), reverse=True)

In the code above, the reverse=True argument tells the sorted() function to sort the elements in descending order.

Sorting by Key vs Sorting by Value

It’s important to note that sorting a dictionary by key is different from sorting it by value. Sorting by key rearranges the dictionary based on the order of the keys, while sorting by value rearranges the dictionary based on the order of the values. The sorted() function can be used to sort a dictionary by value by specifying the key parameter.

my_dict = {'c': 3, 'a': 1, 'b': 2}
sorted_dict_by_value = sorted(my_dict.items(), key=lambda x: x[1])

In the code above, the key parameter is set to a lambda function that extracts the second element from each tuple (the value). This sorts the dictionary items based on the values in ascending order.

Conclusion

Sorting a Python dictionary by key can be done using the sorted() function. By default, the sorted() function sorts elements in ascending order, but you can also sort in descending order by specifying the reverse=True argument. If you want to preserve the original ordering of the dictionary while having a sorted version, you can use the collections.OrderedDict class.