python sorted函数按value值对字典排序

1.sorted(d.items(),key=lambda item:item[1] ,reverse=False)

注意得到的是个list,要得到字典前面加dict()

>>> d={"one":45,"two":24,"three":78,"four":98}
>>> d.items()
dict_items([('one', 45), ('two', 24), ('three', 78), ('four', 98)])
>>> sorted(d.items(),key=lambda item:item[1],reverse=False) 
[('two', 24), ('one', 45), ('three', 78), ('four', 98)]
>>> dict(sorted(d.items(),key=lambda item:item[1],reverse=False) )
{'two': 24, 'one': 45, 'three': 78, 'four': 98}

2.sorted()传入dict时没有加items,则默认比较的是dict的key,所以在key=function()参数x也是dict的key

from collections import Counter
x = Counter({'a':5, 'b':3, 'c':7})
sorted(x)
>>['a', 'b', 'c']
sorted(x.items())
>>[('a', 5), ('b', 3), ('c', 7)]
tf_counter = Counter(gen_tf(data))
    df_counter = Counter(gen_df(data))
    vocab = sorted(df_counter,
              key=lambda x: (df_counter.get(x),tf_counter.get(x)),
              reverse=True)
                   #注意这儿df_counter没加items(),所有lambda后的x默认是key值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值