dict初始化、OrderedDict使用

>>> d = {'a':1, 'b':2}
>>> d
{'a': 1, 'b': 2}
>>> d = dict( (('a',1), ('b',2)) )
>>> d
{'a': 1, 'b': 2}
>>> d = dict(a = 1, b = 2)
>>> d
{'a': 1, 'b': 2}


>>> od = OrderedDict(a=1, b=2, c=3)
>>> od
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> od = OrderedDict(a=1, c=3, b=2)
>>> od
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
#根据进入OrderedDict的顺序排序
>>> od = OrderedDict()
>>> od['z'] = 1
>>> od['y'] = 2
>>> od['x'] = 3
>>> od
OrderedDict([('z', 1), ('y', 2), ('x', 3)])
>>> list(od.keys())
['z', 'y', 'x']


OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:

from collections import OrderedDict

class LastUpdatedOrderedDict(OrderedDict):

    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        if len(self) - containsKey >= self._capacity:  #length before changing(the last line) must be < self._capacity
            last = self.popitem(last=False)
            print('remove:', last)
        if containsKey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key, value))
        OrderedDict.__setitem__(self, key, value)

你可能感兴趣的:(python)