Python OrderedDict的使用案例解析
作者:北京流浪儿 时间:2021-11-20 22:47:25
这篇文章主要介绍了Python OrderedDict的使用案例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
很多人认为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/gide/p/6370082.html
标签:python,ordereddict
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现csv格式文件转为asc格式文件的方法
2021-10-12 19:10:37
![](https://img.aspxhome.com/file/2023/3/72823_0s.jpg)
thinkphp5加layui实现图片上传功能(带图片预览)
2023-06-13 01:09:45
Python实现读取csv文件并进行排序
2021-06-27 08:37:59
python 列表元素左右循环移动 的多种解决方案
2023-06-15 06:21:45
![](https://img.aspxhome.com/file/2023/9/59649_0s.jpg)
python开发一款翻译工具
2022-01-19 07:28:43
![](https://img.aspxhome.com/file/2023/5/72035_0s.png)
关注前端开发流程
2009-12-31 17:38:00
盘点十个超级好用的高级Python脚本
2023-12-04 23:41:27
![](https://img.aspxhome.com/file/2023/0/69630_0s.png)
Jmail发信的实例,模块化随时调用
2007-09-27 13:35:00
Dreamweaver如何制作会移动的广告条
2010-10-20 20:04:00
python 字符串的驻留机制及优缺点
2022-11-16 10:07:37
无法远程登入MySQL数据库的几种解决办法
2012-04-13 11:57:41
python批量读取txt文件为DataFrame的方法
2021-09-29 12:04:21
![](https://img.aspxhome.com/file/2023/6/77786_0s.jpg)
用Pytorch训练CNN(数据集MNIST,使用GPU的方法)
2021-10-12 23:01:01
Python+OCR实现文档解析的示例代码
2023-11-22 02:34:19
![](https://img.aspxhome.com/file/2023/0/82790_0s.jpg)
十个免费的web前端开发工具详细整理
2023-08-12 17:01:22
![](https://img.aspxhome.com/file/2023/3/56013_0s.jpg)
Python执行Linux系统命令的4种方法
2023-08-10 19:04:50
python实现数据预处理之填充缺失值的示例
2022-01-24 19:44:30
![](https://img.aspxhome.com/file/2023/0/83990_0s.jpg)
PHP文件上传功能实现逻辑分析
2023-05-25 02:28:30
Pytorch转tflite方式
2023-08-10 03:47:29
Python之Pygame的Draw绘图
2022-11-29 18:51:18