python模块介绍- collections(5)-OrderedDict 有序字典

长平狐 发布于 2013/12/25 17:23
阅读 18K+
收藏 0

python模块介绍- collections(5)-OrderedDict 有序字典

2013-04-18 磁针石

#承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.com qq 37391319 博客:http://blog.csdn.net/oychw

#版权所有,转载刊登请来函联系

#深圳测试自动化python项目接单群113938272深圳会计软件测试兼职 6089740

#深圳地摊群 66250781武冈洞口城步新宁乡情群49494279

#自动化测试和python群组: http://groups.google.com/group/automation_testing_python

#参考资料:《The Python Standard Libraryby Example 2011》


1.3.5 OrderedDict 有序字典

OrderedDict是dict的子类,它记住了内容添加的顺序。

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 '\nOrderedDict:'

d = collections.OrderedDict()

d['a'] = 'A'

d['b'] = 'B'

d['c'] = 'C'

 

for k, v in d.items():

   print k, v

执行结果:

# ./collections_ordereddict_iter.py

Regular dictionary:

a A

c C

b B

 

OrderedDict:

a A

b B

c C

OrderedDict要内容和顺序完全相同才会视为相等。

import collections

 

print 'dict       :',

d1 = {}

d1['a'] = 'A'

d1['b'] = 'B'

d1['c'] = 'C'

 

d2 = {}

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'

 

d2 = collections.OrderedDict()

d2['c'] = 'C'

d2['b'] = 'B'

d2['a'] = 'A'

 

print d1 == d2

执行结果:

# ./collections_ordereddict_equality.py

dict      : True

OrderedDict: False

 

定义:

class collections.OrderedDict([items])

   注意顺序以添加顺序为准,和修改的顺序无关。

   特殊方法:OrderedDict.popitem(last=True) 。last为True是LIFO,即为堆栈,反之是FIFO,即为队列。还支持排序:reversed().

   有序字典和有序字典的相等比较,是顺序相关的;和其他映射类型比较,是顺序无关的。

手册中的实例:

>>> # regular unsorteddictionary

>>> d = {'banana': 3, 'apple':4,'pear': 1, 'orange': 2}

 

>>> # dictionary sorted by key

>>> OrderedDict(sorted(d.items(),key=lambda t: t[0]))

OrderedDict([('apple', 4), ('banana', 3),('orange', 2), ('pear', 1)])

 

>>> # dictionary sorted by value

>>> OrderedDict(sorted(d.items(),key=lambda t: t[1]))

OrderedDict([('pear', 1), ('orange', 2),('banana', 3), ('apple', 4)])

 

>>> # dictionary sorted bylength of the key string

>>> OrderedDict(sorted(d.items(),key=lambda t: len(t[0])))

OrderedDict([('pear', 1), ('apple', 4),('orange', 2), ('banana', 3)])

如果想根据插入顺序排序:

   classLastUpdatedOrderedDict(OrderedDict):

   'Store items in the order the keys were last added'

 

   def __setitem__(self, key, value):

       if key in self:

           del self[key]

       OrderedDict.__setitem__(self, key, value)

上面已经存在的元素再次插入,就会移动到最后。

还可以与Counter结合,是Counter记住第一次元素出现的顺序。

classOrderedCounter(Counter, OrderedDict):

     'Counter that remembers the order elementsare first encountered'

 

     def __repr__(self):

         return '%s(%r)' % (self.__class__.__name__,OrderedDict(self))

 

     def __reduce__(self):

         return self.__class__, (OrderedDict(self),)

参考资料:

SeeAlso:

collections(http://docs.python.org/library/collections.html) The standard library

documentationfor this module.



原文链接:http://blog.csdn.net/oychw/article/details/8817856
加载中
返回顶部
顶部