首页 > 解决方案 > 如何根据字典的值对字典进行降序排序?

问题描述

orders = {
    'apple: 54,
    'banana': 56,
    'orange': 72,
    'peach': 48,
    'grape': 41
}

给定这种格式的字典,如何按值降序对字典进行排序?

标签: pythondictionary

解决方案


您可以使用 sorted 函数来执行此操作。

orders = {
    'apple': 54,
    'banana': 56,
    'orange': 72,
    'peach': 48,
    'grape': 41
}

d = sorted(orders.items(), key=lambda x:x[1], reverse=True)
print(dict(d))

输出:

{‘橙’:72,‘香蕉’:56,‘苹果’:54,‘桃’:48,‘葡萄’:41}


推荐阅读