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

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

  •  8
  • João Portela  · 技术社区  · 16 年前

    最老的

    :

    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)

    9 回复  |  直到 7 年前
        1
  •  7
  •   JimB    16 年前

    Python字典现在是有序的(从3.6及以上)。 more details
    next(iter(dict)) 将给出最旧的(或第一个)密钥。 stackoverflow answer

    因此,要删除最旧的(或第一个)密钥,我们可以使用以下方法。..

    dict.pop(next(iter(dict)))
    
        2
  •  12
  •   Adrien Plisson    16 年前

    collections.OrderedDict

    append pop

        3
  •  3
  •   Federer    16 年前

    字典不能保持顺序,所以你无法分辨哪个元素是先添加的。你可以把字典和它的关键字列表结合起来,以保持顺序。

    这是一个 activestate recipe 对于一个有秩序的格言来说,它就是这样做的。

    还有 PEP-0372 用这个 patch 对于一个修改类。

        4
  •  3
  •   Denis Otkidach    16 年前

    一种方法是将密钥存储在数组中,这将为您保留顺序。类似于:

    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 == 而不是 > .

        5
  •  2
  •   Jack M.    16 年前

    除非你有某种数量的元素,你知道哪一个是最古老的,否则你可以简单地删除它。否则,我认为你正在做的事情使用了错误的数据结构。

    编辑 this. collections

        6
  •  1
  •   Bryan McLemore    16 年前
        7
  •  0
  •   retracile    16 年前

    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 我一直觉得他们的工作非常出色。

        8
  •  0
  •   YOU    16 年前

    可能对你有用的东西:

    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