Python 字典按值排序

python 字典(dict)默认使用的是只根据 key 排序,如果需要将字典按值排序的话,那可以用下面的几种方法来进行:
我们主要是使用 sorted 函数操作:

def sorted(iterable: Iterable[_T], key: Optional[Callable[[_T], Any]]=..., reverse: bool=...)
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
'''
Args:
	iterable: 表示可以迭代的对象, 可以是dict.items()、dict.keys()等
	key:可选,用来选取参与比较的元素
	reverse:用来指定排序是倒序还是顺序,reverse=True则是倒序,reverse=False时则是顺序,默认为False。
Return:
	返回一个新的按固定顺序排好的列表
'''

方法一:

dict_data = {'a': 12, 'd': 9, 'f': 13, 'b': 25}
new_list = sorted(dict_data.items(), key=lambda item: item[1],reverse=True)
# key=lambda item: item[0] 表示按照key 排序

方法二(推荐):

import operator
dict_data = {'a': 12, 'd': 9, 'f': 13, 'b': 25}
new_list = sorted(dict_data.items(), key=operator.itemgetter(1),reverse=True) 
# key=operator.itemgetter(0) 表示按照key 排序

输出结果:

[('b', 25), ('f', 13), ('a', 12), ('d', 9)]
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值