To sort a dictionary by keys in Python, you can use the `sorted()` function and a dictionary comprehension. This allows you to create a new dictionary with the key-value pairs sorted by key.
We can sort a dictionary by keys in Python using the `sorted()` function and a dictionary comprehension. This example demonstrates how to declare and initialize a dictionary, use the `sorted()` function to sort the dictionary by keys, and print the sorted dictionary.
For example,
my_dict
with integer keys and string values.my_dict = {
3: 'Three',
1: 'One',
2: 'Two'
}
# Sort the dictionary by keys using sorted()
sorted_dict = {k: my_dict[k] for k in sorted(my_dict)}
# Print the sorted dictionary
print('Sorted dictionary:')
for key, value in sorted_dict.items():
print(f'Key: {key}, Value: {value}')
Sorted dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can sort a dictionary by keys in descending order in Python using the `sorted()` function and a dictionary comprehension with the `reverse=True` parameter. This example demonstrates how to declare and initialize a dictionary, use the `sorted()` function to sort the dictionary by keys in descending order, and print the sorted dictionary.
For example,
my_dict
with integer keys and string values.my_dict = {
3: 'Three',
1: 'One',
2: 'Two'
}
# Sort the dictionary by keys in descending order using sorted()
sorted_dict = {k: my_dict[k] for k in sorted(my_dict, reverse=True)}
# Print the sorted dictionary
print('Sorted dictionary:')
for key, value in sorted_dict.items():
print(f'Key: {key}, Value: {value}')
Sorted dictionary: Key: 3, Value: Three Key: 2, Value: Two Key: 1, Value: One
In this tutorial, we learned How to Sort a Dictionary by Keys in Python language with well detailed examples.