Python OrderedDict字典排序方法详解
作者:疯了的小蜗 时间:2022-01-07 13:32:09
很多人认为python中的字典是无序的,因为它是按照hash来存储的,但是python中有个模块collections(英文,收集、集合),里面自带了一个子类
OrderedDict,实现了对字典对象中元素的排序。请看下面的实例:
import collections
print "Regular dictionary"
d={}
d['a']='A'
d['b']='B'
d['c']='C'
for k,v in d.items():
print k,v
print "\nOrder dictionary"
d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d1['1'] = '1'
d1['2'] = '2'
for k,v in d1.items():
print k,v
输出:
Regular dictionary
a A
c C
b B
Order dictionary
a A
b B
c C
1 1
2 2
可以看到,同样是保存了ABC等几个元素,但是使用OrderedDict会根据放入元素的先后顺序进行排序。所以输出的值是排好序的。
OrderedDict对象的字典对象,如果其顺序不同那么Python也会把他们当做是两个不同的对象,请看事例:
print 'Regular dictionary:'
d2={}
d2['a']='A'
d2['b']='B'
d2['c']='C'
d3={}
d3['c']='C'
d3['a']='A'
d3['b']='B'
print d2 == d3
print '\nOrderedDict:'
d4=collections.OrderedDict()
d4['a']='A'
d4['b']='B'
d4['c']='C'
d5=collections.OrderedDict()
d5['c']='C'
d5['a']='A'
d5['b']='B'
print d1==d2
输出:
Regular dictionary:
True
OrderedDict:
False
再看几个例子:
dd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
#按key排序
kd = collections.OrderedDict(sorted(dd.items(), key=lambda t: t[0]))
print kd
#按照value排序
vd = collections.OrderedDict(sorted(dd.items(),key=lambda t:t[1]))
print vd
#输出
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
来源:https://www.cnblogs.com/insane-Mr-Li/p/12779552.html
标签:Python,Ordered,Dict,字典
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅析python的Lambda表达式
2021-11-16 23:51:19
![](https://img.aspxhome.com/file/2023/4/71324_0s.png)
pytorch中图像的数据格式实例
2021-02-16 06:22:19
存贮查询与运行时查询孰优孰劣?
2009-11-01 15:13:00
python执行scp命令拷贝文件及文件夹到远程主机的目录方法
2023-07-10 09:12:19
PHP排序二叉树基本功能实现方法示例
2023-07-10 04:45:53
numpy工程实践之np.savetxt()存储数据
2023-06-19 07:33:11
![](https://img.aspxhome.com/file/2023/5/59655_0s.png)
php通过隐藏表单控件获取到前两个页面的url
2023-11-16 04:00:08
![](https://img.aspxhome.com/file/2023/5/102105_0s.gif)
python3爬虫怎样构建请求header
2023-04-17 19:01:45
![](https://img.aspxhome.com/file/2023/7/68857_0s.png)
Python关于print的操作(倒计时、转圈显示、进度条)
2022-08-19 07:26:58
![](https://img.aspxhome.com/file/2023/2/66282_0s.gif)
python 图像平移和旋转的实例
2021-03-06 23:59:49
ASP + XML + JavaScript 实现动态无限级联动菜单
2008-06-13 06:31:00
二级下拉菜单代码
2008-11-01 18:18:00
asp dictionary对象的用法
2011-04-14 11:09:00
视觉注意力—解剖设计的根源
2010-01-22 15:12:00
![](https://img.aspxhome.com/file/UploadPic/20101/22/visual-attention_banner-59s.jpg)
Python面向对象之继承原理与用法案例分析
2021-06-28 02:07:53
![](https://img.aspxhome.com/file/2023/4/65544_0s.png)
asp如何编写sql语句来查询|搜索数据记录
2008-10-09 12:35:00
也谈网页圆角的背景图法
2009-03-19 14:09:00
![](https://img.aspxhome.com/file/UploadPic/20093/19/k2009313222051-53s.gif)
asp中的rs.open于conn.execute的区别
2009-10-29 12:12:00
python求解水仙花数的方法
2023-10-08 12:07:28
WEB打印分页类(JS)
2008-01-22 14:02:00