1. OrderedDict
  2. 使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
  3. 如果要保持Key的顺序,可以用OrderedDict:
  4. >>> from collections import OrderedDict
  5. >>> d = dict([('a', 1), ('b', 2), ('c', 3)])
  6. >>> d # dict的Key是无序的
  7. {'a': 1, 'c': 3, 'b': 2}
  8. >>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
  9. >>> od # OrderedDict的Key是有序的
  10. OrderedDict([('a', 1), ('b', 2), ('c', 3)])
  11. 注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
  12. >>> od = OrderedDict()
  13. >>> od['z'] = 1
  14. >>> od['y'] = 2
  15. >>> od['x'] = 3
  16. >>> od.keys() # 按照插入的Key的顺序返回
  17. ['z', 'y', 'x']
  18. OrderedDict可以实现一个FIFO(先进先出)的dict,当容量超出限制时,先删除最早添加的Key:
  19. from collections import OrderedDict
  20. class LastUpdatedOrderedDict(OrderedDict):
  21. def __init__(self, capacity):
  22. super(LastUpdatedOrderedDict, self).__init__()
  23. self._capacity = capacity
  24. def __setitem__(self, key, value):
  25. containsKey = 1 if key in self else 0
  26. if len(self) - containsKey >= self._capacity:
  27. last = self.popitem(last=False)
  28. print 'remove:', last
  29. if containsKey:
  30. del self[key]
  31. print 'set:', (key, value)
  32. else:
  33. print 'add:', (key, value)
  34. OrderedDict.__setitem__(self, key, value)
05-07 15:32