To sort a dictionary in Python by keys:
1. In an ascending order:
my_dict = {4: "d", 2: "b", 5: "e", 1: "a", 3: "c"}
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)
Output:
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
2. In a descending order:
my_dict = {4: "d", 2: "b", 5: "e", 1: "a", 3: "c"}
sorted_dict = dict(sorted(my_dict.items(), reverse=True))
print(sorted_dict)
Output:
{5: 'e', 4: 'd', 3: 'c', 2: 'b', 1: 'a'}
Function to sort a dictionary
Here is a function to sort a dictionary in Python by keys:
def sort_dict_by_keys(my_dict: dict, reverse: bool = False) -> dict:
"""
Sorts a dictionary by its keys.
Args:
- my_dict (dict): The dictionary to be sorted.
- reverse (bool, optional): If true, sorts the dictionary in descending order. Default is false.
Returns:
- dict: A new dictionary sorted by keys.
"""
return dict(sorted(my_dict.items(), reverse=reverse))
if __name__ == "__main__":
example_dict = {4: "d", 2: "b", 5: "e", 1: "a", 3: "c"}
sorted_dict_ascending = sort_dict_by_keys(example_dict)
print("Sorted dictionary in ascending order:")
print(sorted_dict_ascending)
sorted_dict_descending = sort_dict_by_keys(example_dict, reverse=True)
print("Sorted dictionary in descending order:")
print(sorted_dict_descending)
The result:
Sorted dictionary in ascending order:
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
Sorted dictionary in descending order:
{5: 'e', 4: 'd', 3: 'c', 2: 'b', 1: 'a'}