In Python, dictionaries are unordered collections of items. However, you can sort a dictionary by its keys or values and create a new sorted dictionary or a list of tuples. Below are some common methods to sort a dictionary in Python.
1. Sorting a Dictionary by Keys
To sort a dictionary by its keys, you can use the sorted()
function, which returns a list of sorted keys. You can then use a dictionary comprehension or convert the sorted list back to a dictionary.
Example:
# Sorting a dictionary by keys
my_dict = {'b': 3, 'a': 2, 'c': 1}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print(sorted_dict)
Output:
{'a': 2, 'b': 3, 'c': 1}
In this example, the dictionary is sorted by its keys in ascending order.
2. Sorting a Dictionary by Values
To sort a dictionary by its values, you can use the sorted()
function with a lambda function to specify that the sorting should be done based on the dictionary’s values.
Example:
# Sorting a dictionary by values
my_dict = {'b': 3, 'a': 2, 'c': 1}
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict)
Output:
{'c': 1, 'a': 2, 'b': 3}
In this example, the dictionary is sorted by its values in ascending order.
3. Sorting a Dictionary by Keys in Descending Order
You can sort the dictionary by keys in descending order by setting the reverse
parameter of the sorted()
function to True
.
Example:
# Sorting a dictionary by keys in descending order
my_dict = {'b': 3, 'a': 2, 'c': 1}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict, reverse=True)}
print(sorted_dict)
Output:
{'c': 1, 'b': 3, 'a': 2}
In this example, the dictionary is sorted by its keys in descending order.
4. Sorting a Dictionary by Values in Descending Order
Similarly, you can sort the dictionary by its values in descending order by setting the reverse
parameter to True
.
Example:
# Sorting a dictionary by values in descending order
my_dict = {'b': 3, 'a': 2, 'c': 1}
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1], reverse=True)}
print(sorted_dict)
Output:
{'b': 3, 'a': 2, 'c': 1}
In this example, the dictionary is sorted by its values in descending order.
5. Sorting a Dictionary by Keys and Values Using OrderedDict
The collections.OrderedDict
can be used to maintain the order of the sorted dictionary.
Example:
from collections import OrderedDict
# Sorting by keys and maintaining order
my_dict = {'b': 3, 'a': 2, 'c': 1}
sorted_dict = OrderedDict(sorted(my_dict.items()))
print(sorted_dict)
Output:
OrderedDict([('a', 2), ('b', 3), ('c', 1)])
In this example, OrderedDict
maintains the order of the sorted items.