集合:高性能的容器类型之OrderedDict objects

来源:互联网 发布:三明治板的刚度矩阵 编辑:程序博客网 时间:2024/06/14 17:17

OrderedDict objects

Ordered dictionaries are just like regular dictionaries but they remember theorder that items were inserted. When iterating over an ordered dictionary,the items are returned in the order their keys were first added.

class collections.OrderedDict([items])

Return an instance of a dict subclass, supporting the usual dictmethods. AnOrderedDict is a dict that remembers the order that keyswere first inserted. If a new entry overwrites an existing entry, theoriginal insertion position is left unchanged. Deleting an entry andreinserting it will move it to the end.

New in version 2.7.

OrderedDict.popitem(last=True)

The popitem() method for ordered dictionaries returns and removesa (key, value) pair. The pairs are returned in LIFO order iflast istrue or FIFO order if false.

In addition to the usual mapping methods, ordered dictionaries also supportreverse iteration usingreversed().
增加了通常的map方法,还支持反转 reversed()

Equality tests between OrderedDict objects are order-sensitive and are implemented aslist(od1.items())==list(od2.items()).Equality tests betweenOrderedDict objects and otherMapping objects are order-insensitive like regular dictionaries. This allows OrderedDict objects to be substitutedanywhere a regular dictionary is used.

判定OrderedDict 对象之间相等,是与排序有关的,实现是list(od1.items())==list(od2.items())。

判定OrderedDict 和其他 Mapping 对象(如一般的dictionaries)之间相等,与排序无关.

因此可以OrderedDict 可以代替通用的dictionariy

OrderedDict Examples and Recipes

# coding=utf-8import collectionsdef main():    # regular unsorted dictionary    d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}    # dictionary sorted by key    print collections.OrderedDict(sorted(d.items(), key=lambda t: t[0]))    # dictionary sorted by value    print collections.OrderedDict(sorted(d.items(), key=lambda t: t[1]))    # dictionary sorted by length of the key string    print collections.OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))if __name__ == '__main__':    main()

The new sorted dictionaries maintain their sort order when entriesare deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.

新的被排序的字典会一直保持他们的排序方式直到实例被删除,但是当新的键值被添加的时候,这些键值会被添加到末尾,排序是不会保持的。

It is also straight-forward to create an ordered dictionary variantthat remembers the order the keys werelast inserted.If a new entry overwrites an existing entry, the original insertion position is changed and moved to the end:

可以直接创建一个有序可变的字典,最后插入完记住排序这些keys,新的序列会覆盖就的序列,原先的插入位置已经改变,被移到了末尾。

class LastUpdatedOrderedDict(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)

An ordered dictionary can be combined with the Counter class so that the counter remembers the order elements are first encountered:

通过使用 Counter 类,排序字典是可以组合的,为计数器记住排序的元素是需要首先计数的。

class OrderedCounter(Counter, OrderedDict):    'Counter that remembers the order elements are first encountered'    def __repr__(self):        return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))    def __reduce__(self):        return self.__class__, (OrderedDict(self),)

参考: https://docs.python.org/2/library/collections.html#collections.OrderedDict

0 0