python字典按照value排序方法
作者:宋宋大人 时间:2021-01-31 06:13:16
python中,我们可以对列表、字符串、元祖中的元素进行排序,那对于字典中的元素可以排序吗?其实对于字典本身我们无法进行排序,但是我们可以对字典按值排序。本文介绍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)
来源:https://www.py.cn/faq/python/22411.html
标签:python,字典,value排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
《写给大家看的设计书》阅读笔记之亲密性原则
2009-07-08 20:02:00
![](https://img.aspxhome.com/file/UploadPic/20097/8/qmx_1-99s.jpg)
python3的数据类型及数据类型转换实例详解
2022-06-30 11:24:45
![](https://img.aspxhome.com/file/2023/7/65447_0s.png)
手把手教你pycharm专业版安装破解教程(linux版)
2023-03-03 08:58:56
![](https://img.aspxhome.com/file/2023/3/97513_0s.png)
python从sqlite读取并显示数据的方法
2022-08-27 22:46:24
python smtplib模块自动收发邮件功能(二)
2023-09-29 19:52:28
![](https://img.aspxhome.com/file/2023/4/107854_0s.png)
IE和Firefox的js兼容性整理
2007-11-21 19:40:00
Python利用Turtle绘制哆啦A梦和小猪佩奇
2022-05-08 08:38:24
![](https://img.aspxhome.com/file/2023/2/77822_0s.png)
ASC码对照表
2008-08-07 13:07:00
网页新窗口打开好不好,数据说话
2008-05-31 17:01:00
![](https://img.aspxhome.com/file/UploadPic/up/2008053117181324.gif)
Python selenium文件上传下载功能代码实例
2021-04-24 07:21:28
![](https://img.aspxhome.com/file/2023/9/109419_0s.png)
pytorch自定义不可导激活函数的操作
2022-07-05 10:09:13
![](https://img.aspxhome.com/file/2023/5/77015_0s.png)
python 如何调用 dubbo 接口
2022-09-28 13:20:13
Javascript学习第一季 三
2008-06-27 13:08:00
神经网络python源码分享
2021-10-07 10:41:00
![](https://img.aspxhome.com/file/2023/0/90790_0s.jpg)
DBA经验:如何进行MySQL数据库表的故障检测
2009-02-12 17:37:00
ASP表单验证方法总结
2007-10-06 22:43:00
Centos6.x服务器配置jdk+tomcat+mysql环境(jsp+mysql)
2023-06-14 12:14:13
![](https://img.aspxhome.com/file/2023/1/67221_0s.png)
Python编写电话薄实现增删改查功能
2021-07-14 21:28:18
Python抓新型冠状病毒肺炎疫情数据并绘制全国疫情分布的代码实例
2022-10-11 23:14:40
![](https://img.aspxhome.com/file/2023/5/80815_0s.png)
centos7 PHP环境搭建 GD库 等插件安装方法
2023-11-05 21:25:38