虽然这是一个添加新答案的旧帖子,但当我遇到类似问题并搜索解决方案时,我来回答了这个问题。
以下是一种简单的方式,我们可以在Python 3(Python 3.6之前的版本)中对字典进行排序。
import collections
d={
"Apple": 5,
"Banana": 95,
"Orange": 2,
"Mango": 7
}
od = collections.OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print(od)
sorted_fruit_list = list(od.keys())
print(sorted_fruit_list)
输出:
OrderedDict([('Orange', 2), ('Apple', 5), ('Mango', 7), ('Banana', 95)])
['Orange', 'Apple', 'Mango', 'Banana']
更新:
从Python 3.6及以后的版本开始,我们可以按其值对字典进行排序。
d={
"Apple": 5,
"Banana": 95,
"Orange": 2,
"Mango": 7
}
sorted_data = {item[0]:item[1] for item in sorted(d.items(), key=lambda x: x[1])}
print(sorted_data)
sorted_fruit_list = list(sorted_data.keys())
print(sorted_fruit_list)
输出:
{'Orange': 2, 'Apple': 5, 'Mango': 7, 'Banana': 95}
['Orange', 'Apple', 'Mango', 'Banana']