You can sort a dictionary by its keys using the sorted()
function along with a custom key function. Here's how you can do it with five examples:
- Sorting a dictionary by its keys in ascending order:
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print(sorted_dict)
- Sorting a dictionary by its keys in descending order:
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict, reverse=True)}
print(sorted_dict)
- Sorting a dictionary by its keys alphabetically:
my_dict = {'banana': 3, 'apple': 1, 'cherry': 2}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print(sorted_dict)
- Sorting a dictionary by its keys numerically:
my_dict = {3: 'c', 1: 'a', 2: 'b'}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
print(sorted_dict)
- Sorting a dictionary by its keys ignoring case:
my_dict = {'B': 2, 'a': 1, 'C': 3}
sorted_dict = {k: my_dict[k] for k in sorted(my_dict, key=lambda x: x.lower())}
print(sorted_dict)
These examples demonstrate different ways of sorting a dictionary by its keys based on different requirements.