python中OrderedDict的使用方法详解
作者:北京流浪儿 时间:2023-08-26 14:00:40
很多人认为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)])
来源:http://www.cnblogs.com/gide/p/6370082.html
标签:python,ordereddict
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MySQL死锁的产生原因以及解决方案
2024-01-26 16:11:40
原生js实现下拉菜单
2024-04-28 09:43:04
![](https://img.aspxhome.com/file/2023/5/132815_0s.png)
未知高度的图片垂直居中
2010-12-17 12:36:00
![](https://img.aspxhome.com/file/UploadPic/201012/17/01-22s.jpg)
Windows2012配置SQLServer2014AlwaysOn的图解
2024-01-16 15:39:01
![](https://img.aspxhome.com/file/2023/7/96157_0s.png)
go doudou开发gRPC服务快速上手实现详解
2024-05-05 09:33:11
![](https://img.aspxhome.com/file/2023/7/127467_0s.png)
GO语言异常处理机制panic和recover分析
2024-02-18 01:58:36
品牌的统一体验
2010-05-19 13:08:00
![](https://img.aspxhome.com/file/UploadPic/20105/19/bue-01-70s.jpg)
asp用err.raise自定义错误信息
2007-09-12 19:38:00
python两个_多个字典合并相加的实例代码
2023-05-05 07:50:33
从零开始学Python第八周:详解网络编程基础(socket)
2023-09-04 05:16:20
Sql Server 2005 默认端口修改方法
2024-01-27 08:44:53
Microsoft VBScript 运行时错误 错误 800a0005 无效的过程调用或参数: chr
2011-03-09 11:03:00
全面了解CSS内置颜色(color)值
2008-11-19 12:26:00
MS SQL7.0的数据迁移到MySQL上的一种方法
2008-11-01 16:59:00
python实现猜数字游戏(无重复数字)示例分享
2023-12-15 19:48:46
Python可视化神器pyecharts绘制水球图
2023-10-07 14:19:41
![](https://img.aspxhome.com/file/2023/4/102954_0s.png)
详解Python中的数据清洗工具flashtext
2021-10-05 01:59:47
![](https://img.aspxhome.com/file/2023/5/69645_0s.png)
Python计算双重差分模型DID及其对应P值使用详解
2022-08-06 21:07:53
![](https://img.aspxhome.com/file/2023/5/68335_0s.jpg)
用ASP实现分级权限控制
2008-10-09 13:02:00
Python使用正则匹配实现抓图代码分享
2021-09-06 10:47:28