When it is required to sort the key and values in a dictionary, the ‘sorted’ method can be used.
Below is the demonstration of the same −
Example
my_dict = {'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]} print("The dictionary is : ") print(my_dict) my_result = dict() for key in sorted(my_dict): my_result[key] = sorted(my_dict[key]) print("The sorted dictionary is : " ) print(my_result)
Output
The dictionary is : {'Hi': [1, 6, 3], 'there': [2, 9, 6], 'Mark': [16, 7]} The sorted dictionary is : {'Hi': [1, 3, 6], 'Mark': [7, 16], 'there': [2, 6, 9]}
Explanation
A dictionary is defined, and is displayed on the console.
An empty dictionary is defined.
The dictionary is iterated over, before which it is sorted.
The key is again sorted and assigned to the empty dictionary.
The sorted dictionary is displayed on the console.