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

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. An OrderedDict 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 if last istrue or FIFO order if false.

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

Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()).Equality tests between OrderedDict 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-8
import collections


def 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 were last 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VCHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值