首页 > 解决方案 > Python:仅保留最后 n 个插入键的字典

问题描述

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

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

标签: pythondictionarydata-structures

解决方案


用于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)

推荐阅读