python dic字典排序


使用lambda匿名函数来实现。

>>> dic1 = {'a':1,'b':2,'e':5,'d':4,'c':3}
>>> result = sorted(dic1.items(), key = lambda x :(x[1]))
>>> result
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
>>> result = sorted(dic1.items(), key = lambda x :(-x[1]))
>>> result
[('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]
>>> dic1
{'a': 1, 'b': 2, 'e': 5, 'd': 4, 'c': 3}
>>> result = sorted(dic1.items(), key = lambda x :(x[0]))
>>> result
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
>>> result = sorted(dic1.items(), key = lambda x :(x[0]),reverse = True)
>>> result
[('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)]

#x[0] 用字典的第一位排序
#x[1] 用字典的第二位排序
#-x[0] 用第一位的负数排序

默认是升序
reverse = True 降序

这个用的比较多,先记录一下。写给自己看。


读书和健身总有一个在路上


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM