首页 > 代码库 > Python OrderedDict使用

Python OrderedDict使用

一、最近最少使用实现:

import collections
class LRUDict(object):
    ‘‘‘
    最近最少使用队列实现,最近使用的键值放后面
    ‘‘‘
    def __init__(self,dict_list,size):
        self.ordered_dict = collections.OrderedDict(dict_list)
        self.size = size

    def get(self,key):
        if key in self.ordered_dict:
            value = http://www.mamicode.com/self.ordered_dict.get(key)>

OR:

class LRUDict(collections.OrderedDict):
    def __init__(self, size, *args, **kwargs):
        self.size = size
        super(LRUDict, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        if key in self:
            self.move_to_end(key)
        return super(LRUDict, self).__getitem__(key)

    def __setitem__(self, key, value):
        if len(self) >= 10:
            self.popitem(last=False)
        super(LRUDict, self).__setitem__(key, value)
        self.move_to_end(key)


instance = LRUDict(4, [(1, 1), (2, 2), (3, 3)])
print(instance[1], instance)
instance.update([(4, 4)])
print(instance)
instance.update([(3, 9)])
print(instance)

  

Python OrderedDict使用