Python日常-字典排序
2017-01-21 16:06
204 查看
python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行:
输出的结果:
下面我们分解下代码
print dic.iteritems() 得到[(键,值)]的列表。
然后用sorted方法,通过key这个参数,指定排序是按照value,也就是第一个元素d[1的值来排序。reverse = True表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。
1. 按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表示是需要翻转的,默认是从小到大,翻转的话,那就是从大到小。
2. 按key排序
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0} dict= sorted(dic.iteritems(), key=lambda d:d[0]) d[0]表示字典的键 print dict
相关文章推荐
- Python中最快的字典排序方法
- python天天进步(4)--字典排序
- python学习:读写文件和字典排序
- 三、Python的字典排序
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- python日常学习总结
- 传说中最快的python字典排序方法
- python字典排序
- Python中 字典排序、列表排序
- python天天进步(3)--字典排序
- Python中 字典排序、列表排序
- 看看360的同学日常是怎么使用python的
- python的排序函数sort,sorted在列表排序和字典排序中的应用详解和举例
- python 字典排序
- python字典排序
- python字典排序
- Python字典排序及简单性能测试
- Python MysqlDB 日常使用模板
- Python-向飞信好友发送短信,可用于日常监控程序
- Python中 字典排序、列表排序