How do I sort a dictionary by its keys? Example input: {2:3, 1:89, 4:5, 3:0} Desired output: {1:89, 2:3, 3:0, 4:5}
In Python, you can sort a dictionary by its keys using the sorted()
function along with a custom sorting key. Here's how you can sort a dictionary by its keys in ascending order:
python
input_dict = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_dict = dict(sorted(input_dict.items()))
print(sorted_dict)
Output:
yaml
{1: 89, 2: 3, 3: 0, 4: 5}
In this example, the sorted()
function is used to sort the dictionary's items based on their keys. The items()
method is used to convert the dictionary items into a list of key-value pairs. The dict()
constructor is then used to convert the sorted list of key-value pairs back into a dictionary.
If you want to sort the dictionary in descending order, you can use the reverse
parameter of the sorted()
function:
python
input_dict = {2: 3, 1: 89, 4: 5, 3: 0}
sorted_dict_descending = dict(sorted(input_dict.items(), reverse=True))
print(sorted_dict_descending)
Output:
yaml
{4: 5, 3: 0, 2: 3, 1: 89}
In both cases, the sorted()
function sorts the dictionary items based on their keys, and the result is then converted back into a dictionary using the dict()
constructor.
Comments
Post a Comment