python模块简介之有序字典(OrderedDict)
2016-12-01 00:00
841 查看
有序字典-OrderedDict简介
示例
有序字典和通常字典类似,只是它可以记录元素插入其中的顺序,而一般字典是会以任意的顺序迭代的。参见下面的例子:
运行结果如下:
可以看到通常字典不是以插入顺序遍历的。
相等性
判断两个有序字段是否相等(==)需要考虑元素插入的顺序是否相等
运行结果如下:
而当判断一个有序字典和其它普通字典是否相等只需判断内容是否相等。
注意
OrderedDict 的构造器或者 update() 方法虽然接受关键字参数,但因为python的函数调用会使用无序的字典来传递参数,所以关键字参数的顺序会丢失,所以创造出来的有序字典不能保证其顺序。
参考资料
https://docs.python.org/2/library/collections.html#collections.OrderedDict
https://pymotw.com/2/collections/ordereddict.html
示例
有序字典和通常字典类似,只是它可以记录元素插入其中的顺序,而一般字典是会以任意的顺序迭代的。参见下面的例子:
import collections print 'Regular dictionary:' d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' d['d'] = 'D' d['e'] = 'E' for k, v in d.items(): print k, v print '\nOrderedDict:' d = collections.OrderedDict() d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' d['d'] = 'D' d['e'] = 'E' for k, v in d.items(): print k, v
运行结果如下:
-> python test7.py Regular dictionary: a A c C b B e E d D OrderedDict: a A b B c C d D e E
可以看到通常字典不是以插入顺序遍历的。
相等性
判断两个有序字段是否相等(==)需要考虑元素插入的顺序是否相等
import collections print 'dict :', d1 = {} d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d1['d'] = 'D' d1['e'] = 'E' d2 = {} d2['e'] = 'E' d2['d'] = 'D' d2['c'] = 'C' d2['b'] = 'B' d2['a'] = 'A' print d1 == d2 print 'OrderedDict:', d1 = collections.OrderedDict() d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d1['d'] = 'D' d1['e'] = 'E' d2 = collections.OrderedDict() d2['e'] = 'E' d2['d'] = 'D' d2['c'] = 'C' d2['b'] = 'B' d2['a'] = 'A' print d1 == d2
运行结果如下:
-> python test7.py dict : True OrderedDict: False
而当判断一个有序字典和其它普通字典是否相等只需判断内容是否相等。
注意
OrderedDict 的构造器或者 update() 方法虽然接受关键字参数,但因为python的函数调用会使用无序的字典来传递参数,所以关键字参数的顺序会丢失,所以创造出来的有序字典不能保证其顺序。
参考资料
https://docs.python.org/2/library/collections.html#collections.OrderedDict
https://pymotw.com/2/collections/ordereddict.html
您可能感兴趣的文章:
Python的collections模块中的OrderedDict有序字典相关文章推荐
- python模块简介之有序字典(OrderedDict)
- Python的collections模块中的OrderedDict有序字典
- Python的collections模块中的OrderedDict有序字典
- python模块介绍- collections(5)-OrderedDict 有序字典
- Python的collections模块中的OrderedDict有序字典
- Python的collections模块中的OrderedDict有序字典
- python 有序字典OrderedDict
- Python 有序字典简介
- Python 有序字典简介
- Python3 有序字典—OrderedDict()
- 【python】collections模块(有序字典,计数器,双向队列)
- python的collection系列-有序字典(OrderedDict)
- python 2-6 如何让字典保持有序collections.OrderedDict
- python中的有序字典OrderedDict
- python 常用模块简介和安装
- Python sys模块简介
- Python模块简介之threading模块
- python有序字典
- python json模块 字典 输出中文
- OrderedDict 有序字典以及读取json串时如何保持原有顺序