脚本专栏 
首页 > 脚本专栏 > 浏览文章

Python实现字典依据value排序

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

具体内容如下:

使用sorted将字典按照其value大小排序

> record = {'a':89, 'b':86, 'c':99, 'd':100}
> sorted(record.items(), key=lambda x:x[1])
[('b', 86), ('a', 89), ('c', 99), ('d', 100)]

sorted第一个参数要可迭代,可以为tuple, list

> items = [(1, 'B'), (1, 'A'), (2, 'A'), (0, 'B'), (0, 'a')]
> sorted(items)
[(0, 'B'), (0, 'a'), (1, 'A'), (1, 'B'), (2, 'A')]

为什么(0, 'B')在(0, 'a')前面?

因为ASCII码中大写字母排在在小写字母前面,使用str.lower()方法改变其顺序

> sorted(items, key=lambda x:(x[0], x[1].lower()))
[(0, 'a'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A')]

以上内容是关于Python实现字典依据value排序的相关知识,希望对大家有所帮助!

上一篇:python脚本设置系统时间的两种方法
下一篇:python脚本设置超时机制系统时间的方法
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网