python 按字典value排序以及按list中字典的某个key的value排序

python 按字典value排序以及按list中字典的某个key的value排序

1. 按照字典value排序

student_1={'a':2,'b':4,'c':6,'d':8}
student_1_sort = sorted(student_1.items(), key=lambda d: d[1], reverse=True)
print(student_1_sort)

输出:

[('d', 8), ('c', 6), ('b', 4), ('a', 2)]

2. 按list中字典的某个key的value排序

student_2 = [
    {"no": 1, "score": 90},
    {"no": 2, "score": 90},
    {"no": 3, "score": 88},
    {"no": 4, "score": 92},
    ]
print("original: {0}".format(student_2))

输出:

original: [{'no': 1, 'score': 90}, {'no': 2, 'score': 90}, {'no': 3, 'score': 88}, {'no': 4, 'score': 92}]
# 单级排序,仅按照score排序
student_2_sort_1 = sorted(student_2, key=lambda e: e.__getitem__('score'))
print("sort by 1 key: ", student_2_sort_1)

输出:

sort by 1 key:  [{'no': 3, 'score': 88}, {'no': 1, 'score': 90}, {'no': 2, 'score': 90}, {'no': 4, 'score': 92}]
# 多级排序,先按照score,再按照no排序
student_2_sort_2 = sorted(student_2, key=lambda e:(e.__getitem__('score'), e.__getitem__('no')))
print("sort by 2 keys: ", student_2_sort_2)

输出:

sort by 2 keys:  [{'no': 3, 'score': 88}, {'no': 1, 'score': 90}, {'no': 2, 'score': 90}, {'no': 4, 'score': 92}]

作者:DreamLee0625
来源:CSDN
原文:https://blog.csdn.net/vitaminc4/article/details/78791437
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值