gpt4 book ai didi

python - 在字典中临时保留键和值

转载 作者:行者123 更新时间:2023-12-05 00:43:14 25 4
gpt4 key购买 nike

我有一个不时添加信息的python字典。

条件:

  1. 字典中应始终有 3 个或更少的键。如果需要再添加一个键值对,则应删除此时字典中最早添加的键,并添加新的键。
  2. 添加键值对后,1 天后应将其删除。

例子:

result = {}

def add_key(key, val):
test = result.get(key) # Test to see if key already exists
if test is None:
if len(result.keys()) < 3:
result[key] = val # This key and pair need to be deleted from the dictionary after
# 24 hours
else:
# Need code to remove the earliest added key.

add_key('10', 'object 2')

## Need another code logic to delete the key-value pair after 24 hours

我应该如何处理这个问题?

最佳答案

以下是我在 comment 中推荐的方法在你的问题下 - 即通过实现一个字典子类来做到这一点,该字典子类通过它内部维护的关于它包含的每个值的元数据来完成所需的工作。

这可以通过abstract base classes for containers 轻松完成。在 collections.abc 模块中,因为它最大限度地减少了需要在子类中实现的方法的数量。在这种情况下,abc.MutableMapping 用于基类。

请注意,我添加了一个名为 prune() 的新方法,它显示了如何删除所有早于指定数量的条目。除此之外,我还在代码中留下了一些对 print() 的无关调用,以便在测试时更清楚地了解它所做的事情——您可能希望将其删除。

from collections import abc
from datetime import datetime, timedelta
from operator import itemgetter
from pprint import pprint
from time import sleep


class LimitedDict(abc.MutableMapping):
LIMIT = 3

def __init__(self, *args, **kwargs):
self._data = dict(*args, **kwargs)

if len(self) > self.LIMIT:
raise RuntimeError(f'{type(self).__name__} initialized with more '
f'than the limit of {self.LIMIT} items.')

# Initialize value timestamps.
now = datetime.now()
self._timestamps = {key: now for key in self._data.keys()}

def __getitem__(self, key):
return self._data[key]

def __setitem__(self, key, value):
if key not in self: # Adding a key?
if len(self) >= self.LIMIT: # Will doing so exceed limit?
# Find key of oldest item and delete it (and its timestamp).
oldest = min(self._timestamps.items(), key=itemgetter(1))[0]
print(f'deleting oldest item {oldest=} to make room for {key=}')
del self[oldest]

# Add (or update) item and timestamp.
self._data[key], self._timestamps[key] = value, datetime.now()

def __delitem__(self, key):
"""Remove item and associated timestamp."""
del self._data[key]
del self._timestamps[key]

def __iter__(self):
return iter(self._data)

def __len__(self):
return len(self._data)

def prune(self, **kwargs) -> None:
""" Remove all items older than the specified maximum age.

Accepts same keyword arguments as datetime.timedelta - currently:
days, seconds, microseconds, milliseconds, minutes, hours, and weeks.
"""
max_age = timedelta(**kwargs)
now = datetime.now()
self._data = {key: value for key, value in self._data.items()
if (now - self._timestamps[key]) <= max_age}
self._timestamps = {key: self._timestamps[key] for key in self._data.keys()}



if __name__ == '__main__':

ld = LimitedDict(a=1, b=2)
pprint(ld._data)
pprint(ld._timestamps)
sleep(1)
ld['c'] = 3 # Add 3rd item.
print()
pprint(ld._data)
pprint(ld._timestamps)
sleep(1)
ld['d'] = 4 # Add an item that should cause limit to be exceeded.
print()
pprint(ld._data)
pprint(ld._timestamps)
ld.prune(seconds=2) # Remove all items more than 2 seconds old.
print()
pprint(ld._data)
pprint(ld._timestamps)

关于python - 在字典中临时保留键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70593677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com