Python:只保留最后n个插入键的字典

2024-04-20 02:02:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Python中是否有一个数据结构已经实现了这种行为?我想在重新发明轮子之前检查一下。你知道吗


Tags: 文件路径数据结构内容字典磁盘轮子计划
3条回答

您可以使用^{}及其方法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)])

对于我的特殊问题,由于我需要从磁盘读取文件,我想我将使用lru缓存,正如@PatrickHaugh建议的那样。有一种方法可以使用缓存:

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,这是完美的。你知道吗

为此使用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)

相关问题 更多 >