Issue
I want to sort the values of this dictionary from low to high:
For example, input:
average = {'ali': 7.83, 'mahdi': 13.4, 'hadi': 16.2, 'hasan': 3.57}
I want the output to be like this:
{'hasan': 3.57, 'ali': 7.83, 'mahdi': 13.4, 'hadi': 16.2}
I tested this method, but because my data is decimal, it gives an error:
dict(sorted(average.items(), key=lambda item: item[1]))
Error:
ave_dict_sort = dict(sorted(average.items(), key=lambda item: item[1]))
^^^^^^^^^^^^^
AttributeError: 'float' object has no attribute 'items'
Solution
You can use the sorted function along with a lambda function as the key to achieve this. Here's an example of how you can sort the dictionary by values in ascending order:
average = {'ali': 7.83, 'mahdi': 13.4, 'hadi': 16.2, 'hasan': 3.57}
sorted_average = dict(sorted(average.items(), key=lambda item: item[1]))
print(sorted_average)
This will output:
{'hasan': 3.57, 'ali': 7.83, 'mahdi': 13.4, 'hadi': 16.2}
Here, sorted(average.items(), key=lambda item: item[1]) sorts the dictionary items based on their values (item[1]), and dict() is used to convert the sorted items back into a dictionary.
Answered By - Zohair
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.