python dict排序之一
2014-01-13 21:26
309 查看
python dict的特点就是无序的,按照key来提取相应value,如果我们需要对value进行排序的话,那python dict排序可以按照下面的方法来进行:
下面的是按照value的值从大到小的顺序来排序。
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict
输出的结果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
下面我们分解下代码
print dic.iteritems() 得到[(键,值)]的列表。
然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。
下面的是按照value的值从大到小的顺序来排序。
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict
输出的结果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]
下面我们分解下代码
print dic.iteritems() 得到[(键,值)]的列表。
然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。
相关文章推荐
- python中的mro
- Python画图
- python3自动下载优酷视频小程序
- Python从txt文件中逐行读取数据
- Python标准库 正则表达式 (re包)
- python xpath lxml调试
- Python GUI
- (转) Eclipse - Python - Installation of PyDev with a Python Hello World tutorial
- Python学习之基础数据部分
- Python学习7:装饰器
- python-markdown用法
- 设置 Sublime Text 的 Python 开发环境
- Python 2.7.3 Time与DateTime格式化
- python subprocess Popen
- Python.h:No such file or directory
- Python.h:No such file or directory
- Python.h:No such file or directory
- Python.h:No such file or directory
- python调用cmd命令行制作刷博器
- python 脚本发送邮件