python 字典(dict)按键和值排序
来源:互联网 发布:淘宝卖家强制取消订单 编辑:程序博客网 时间:2024/05/22 07:41
python 字典(dict)的特点就是无序的,按照键(key)来提取相应值(value),如果我们需要字典按值排序的话,那可以用下面的方法来进行:
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
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
1 0
- python 字典(dict)按键和值排序
- python 字典(dict)按键和值排序
- python 字典(dict)按键和值排序
- 字典(dict)按键(key)和值(value)排序
- python 字典(dict)按值排序
- Python字典按键和值排序(转)
- python 中 列表(list)和字典(dict)数据排序
- 列表(list)和字典(dict)数据排序 Python
- python中列表(list)和字典(dict)数据排序
- python字典按键或值排序
- Python dict(字典)和 set
- 列表(list)和字典(dict)数据排序
- python入门--字典dict和集合set
- python中字典按键或键值排序
- python中字典按键或键值排序
- Python中dict 字典
- python dict字典
- python dict字典
- Java开发中的23种设计模式详解
- Sicily 1515. 魔版C
- 学习OpenCV读书笔记——第二章
- Filter
- 第二周 项目三 时间类(1)
- python 字典(dict)按键和值排序
- 多益网络2015校园招聘第二次笔试题
- 欧拉函数以部分性质
- 实时更新widget
- redmine 导出中文乱码
- 编译原理之DFA自动机的
- 使用Xcode自带的单元测试
- Beautiful Soup(三)--搜索文档树
- hdu5050(Java大数 + 二进制 + 最大公约数)