字典(dict)是一种无序的数据结构,它没有内在的排序。可以使用 sorted() 函数并传递字典的 items() 方法作为参数,并指定 key 参数为一个函数,该函数会根据字典的值进行排序。以下是测试过的代码:
dict_demo = {'a': 98, 'b': 20, 'c': 56, 'd': 79, 'e': 43, 'f': 15}
sorted_values = sorted(dict_demo.items(), key=lambda x: x[1])
dict_sorted_by_value = dict(sorted_values)
print(dict_sorted_by_value)