代码之家  ›  专栏  ›  技术社区  ›  João Portela

如何从字典中删除最旧的元素?

  •  3
  • João Portela  · 技术社区  · 15 年前

    我想知道移除 最老的 字典中的元素,以控制最大字典大小。

    例子 :

    MAXSIZE = 4
    dict = {}
    def add(key,value):
      if len(dict) == MAXSIZE:
        old = get_oldest_key() # returns the key to the oldest item
        del dict[old]
      dict[key] = value
    
    add('a','1') # {'a': '1'}
    add('b','2') # {'a': '1', 'b': '2'}
    add('c','3') # {'a': '1', 'c': '3', 'b': '2'}
    add('d','4') # {'a': '1', 'c': '3', 'b': '2', 'd': '4'}
    add('e','5') # {'c': '3', 'b': '2', 'e': '5', 'd': '4'}
    

    这清楚了吗?

    编辑: 忘了 len(dict) 落后一项。

    8 回复  |  直到 6 年前
        1
  •  7
  •   JimB    15 年前

    字典不保留顺序,因此您无法确定先添加了哪个元素。你可以把字典和它的键列表结合起来以保持顺序。

    这里有一个 activestate recipe 为了一个有秩序的口述,就这样做。

    还有 PEP-0372 用这个 patch 对于Odict类。

        2
  •  12
  •   Adrien Plisson    15 年前

    python 3.1有一个有序的dict。 collections.OrderedDict 保持元素的插入顺序。注意,如果您覆盖了一个元素,它会保持其位置的顺序,您需要删除并重新插入一个元素,使其持久。

    如果您使用的是旧版本,则可以使用补丁来获取订单信息。

    无论如何,如果它不可用,您可以简单地使用元组列表:它可以很容易地转换为字典和字典,保持其顺序,可以像队列一样使用 append pop ,…

        3
  •  3
  •   Federer    15 年前

    除非您有某种类型的元素集,其中您知道哪个是最早的,那么您可以简单地删除它。否则,我认为您使用的数据结构是错误的。

    编辑 但是,根据一个快速的谷歌,我遇到了 this. 哦,我确实喜欢 collections 模块:

        4
  •  3
  •   Denis Otkidach    15 年前

    我相信 LRU dict-like container 将满足您的需求。

        5
  •  2
  •   Jack M.    15 年前

    一种方法是将键存储在数组中,这样可以为您保留顺序。类似:

    MAXSIZE = 4
    dict = {}
    history = []
    def add(key,value):
        print len(dict)
        if len(dict) == MAXSIZE:
            old = history.pop(0) # returns the key to the oldest item
            del dict[old]
        history.append(key)
        dict[key] = value
    

    另外,记住 len() 总是落后一项。添加第五个项目时, len(dict) 4 不是 5 . 你应该使用 == 而不是 > .

        6
  •  1
  •   Bryan McLemore    15 年前

    或者,也可以使用元组列表。

    MAXSIZE = 4
    stack = []
    
    def add(key, value):
     stack.append((key, value))
     if len(stack) > MAXSIZE:
      stack.pop(0)
    
     print stack
    
    add('a','1')
    add('b','2')
    add('c','3')
    add('d','4')
    add('e','5')
    

    结果在

    [('a', '1')]
    [('a', '1'), ('b', '2')]
    [('a', '1'), ('b', '2'), ('c', '3')]
    [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
    [('b', '2'), ('c', '3'), ('d', '4'), ('e', '5')]
    

    注意,使用此方法会降低字典查找的速度。所以,如果您需要的话,定制的字典可能是有序的。

    您可以通过Pocoo团队找到一个实现 here . 我一直觉得他们的工作很出色。

        7
  •  0
  •   retracile    15 年前

    不知道你真正想用这个结构做什么,这里是 对你有用的东西:

    class DictCache:
        def __init__(self, maxcount=4):
            self.data = {}
            self.lru = []
            self.maxcount = maxcount
        def add(self, key, value):
            self.data[key] = value
            self.lru.append(key)
            if len(self.lru) > self.maxcount:
                dead = self.lru.pop(0)
                del(self.data[dead])
    

    将此与 get 重新排列的方法 self.lru 当它们被访问时,您可以更改缓存策略以适应 使用。

        8
  •  0
  •   YOU    15 年前

    这样怎么样?将顺序放入数组中,当其达到极限时,将其弹出。

    MAXSIZE = 4
    dict,order= {},[]
    
    def add(key,value):
        if len(dict) > MAXSIZE:
            old = order.pop() # returns the key to the oldest item
            del dict[old]
        order.insert(0,key)
        dict[key] = value