python 对字典按照value进行排序

python中一般对字典按照key随机排序,实际应用中我们可能需要根据value排序,大致的有如下几种方法:

1、内置sorted函数排序

from random import randint
随机创建字典
dict1 = {x:randint(60,100) for x in 'shdlqa'}
print(dict1)
# 从大到小排序
dict2 = sorted(dict1.items(), key=lambda x:x[1], reverse=True)
print(dict2)
#默认从小到大排序
dict3 = sorted(dict1.items(), key=lambda x:x[1])
print(dict3)

输出结果如下:
{'s': 72, 'h': 71, 'd': 90, 'l': 77, 'q': 64, 'a': 87}
[('d', 90), ('a', 87), ('l', 77), ('s', 72), ('h', 71), ('q', 64)]
[('q', 64), ('h', 71), ('s', 72), ('l', 77), ('a', 87), ('d', 90)]

2、利用operator和sorted函数排序

from random import randint
import operator
dict1 = {x:randint(60,100) for x in 'shdlqa'}
print(dict1)
#默认从小打到排序
dict4 = sorted(dict1.items(), key=operator.itemgetter(1))
print(dict4)

#输出结果如下:
{'s': 72, 'h': 71, 'd': 90, 'l': 77, 'q': 64, 'a': 87}
[('q', 64), ('h', 71), ('s', 72), ('l', 77), ('a', 87), ('d', 90)]

3、利用zip元祖排序

from random import randint
dict1 = {x:randint(60,100) for x in 'shdlqa'}
print(dict1)
# 利用zip分装成元祖排序
data = zip(dict1.values(), dict1.keys())
#默认从小到大排序
dict5 = sorted(data)
print(dict5)

#输出结果如下:
{'s': 72, 'h': 71, 'd': 90, 'l': 77, 'q': 64, 'a': 87}
[(64, 'q'), (71, 'h'), (72, 's'), (77, 'l'), (87, 'a'), (90, 'd')]

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值