How to sort a Python dictionary by values’ magnitude?
To sort it by the values in the dictionary, you can use the sorted() function and lambda expression. Here is an example code:
# 定义一个字典
my_dict = {'a': 10, 'b': 5, 'c': 15, 'd': 20}
# 使用sorted函数和lambda表达式按值的大小对字典进行排序
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print(sorted_dict)
The output is:
{'b': 5, 'a': 10, 'c': 15, 'd': 20}
In this example, the lambda expression lambda x: x[1] is passed into the sorted() function as the key parameter, indicating a sorting based on the values in the dictionary (i.e. x[1]). The sorted() function will return a sorted list of tuples, which can then be converted back into dictionary form using the dict() function.