【问题标题】:Python: Dictionary that only retains last n inserted keysPython:仅保留最后 n 个插入键的字典
【发布时间】:2018-06-30 14:01:35
【问题描述】:

我计划从磁盘读取数百万个小文件。为了最小化 i/o,我计划使用一个将文件路径映射到其内容的字典。不过,我只希望字典保留插入其中的最后 n 个键(因此字典将充当缓存)。

Python 中是否存在已经实现此行为的数据结构?我想在重新发明轮子之前检查一下。

【问题讨论】:

  • 如果你想关闭这个,请留言说明原因吗?
  • 看起来很像 LRU 缓存。您可能想深入了解functools.lru_cache 的内部结构,看看它是如何在那里实现的。
  • 哇谢谢@PatrickHaugh lru_cache 看起来很棒。这可能是我想要的解决方案。再深入一点……

标签: python dictionary data-structures


【解决方案1】:

为此使用collections.deque,maxlen 为 6,这样它只存储最后 6 个元素并将信息存储为键值对

from collections import deque
d = deque(maxlen=6)
d.extend([(1,1),(2,2),(3,3),(4,4), (5,5), (6,6)])
d
# deque([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)], maxlen=6)
d.extend([(7,7)])
d
# deque([(2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7)], maxlen=6)

【讨论】:

  • deque 将如何帮助像字典一样保存映射?我是否误读了问题?
  • 您可以在双端队列中存储任何内容,就像列表一样,我建议将映射(键、值对)存储为每个元素
  • 知道了,但要付出代价,即丢失 O(1) 查找。
【解决方案2】:

对于我的特殊问题,由于我需要从磁盘读取文件,我想我会按照@PatrickHaugh 的建议使用 lru 缓存。这是使用缓存的一种方法:

from functools import lru_cache

@lru_cache(maxsize=10)
def read_file(file_path):
  print(' * reading', file_path)
  return file_path # update to return the read file

for i in range(100):
  if i % 2 == 0:
    i = 0 # test that requests for 0 don't require additional i/o
  print(' * value of', i, 'is', read_file(i))

输出显示对 0 的请求不会产生额外的 i/o,这是完美的。

【讨论】:

    【解决方案3】:

    您可以使用collections.OrderedDict 及其方法popitem 确保只保留添加到字典中的最后n 个键。用popitem 指定last=False 确保行为是“FIFO”,即先进先出。这是一个简单的例子:

    from collections import OrderedDict
    
    n = 3
    d = OrderedDict()
    
    for i in range(5):
        if len(d) == n:
            removed = d.popitem(last=False)
            print(f'Item removed: {removed}')
        d[i] = i+1
    
    print(d)
    
    Item removed: (0, 1)
    Item removed: (1, 2)
    OrderedDict([(2, 3), (3, 4), (4, 5)])
    

    【讨论】:

    • 谢谢@jpp!那么last=False 会从键列表的开头弹出(按插入时间排序)?如果是这样,那就完美了。
    • @duhaime,是的,这正是它的作用。 OrderedDict 按插入排序。
    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2013-04-14
    • 2023-03-30
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多