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

时间:2021-12-23 23:36:57

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