最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
python字典按照value排序方法代码示例
时间:2020-12-28 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下python字典按照value排序方法代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
方法一:key使用lambda匿名函数取value进行排序
dict= {'a':1,'b':4,'c':2} sorted(dict.items(),key = lambda x:x[1],reverse = True)
方法二:使用operator的itemgetter进行排序
test_data_6=sorted(dict_data.items(),key=operator.itemgetter(1)) test_data_7=sorted(dict_data.items(),key=operator.itemgetter(1),reverse=True) print(test_data_6) #[(8, 2), (10, 5), (7, 6), (6, 9), (3, 11)] print(test_data_7) #[(3, 11), (6, 9), (7, 6), (10, 5), (8, 2)]
方法三:key和value分装成元祖,再进行排序
f = zip(d.keys(), d.values()) c = sorted(f) print(c)
字典按value排序内容扩展:
保存为字典后,按字典的value值大小排序,这个才是本题的难点,由于dict是无序的,所以只能用list去排序,把dict的key和value保存为tuplue对象
# 对字典按value排序 a = sorted(d.items(), key=lambda x: x[1], reverse=True) print(a)
参考代码:
# coding:utf-8 # 作者:上海-悠悠 a = ["a", "b", "a", "c", "a", "c", "b", "d", "e", "c", "a", "c"] # set集合去重 duixiang = set(a) # 先去重,取出计数对象 # 保存为dict,一一对应 d = {} for i in duixiang: d[i] = a.count(i) # 对字典按value排序 a = sorted(d.items(), key=lambda x: x[1], reverse=True) print(a)
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27