You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除Python字典中最早(第一个)条目以维持固定容量大小

解决方案

Python 3.7及以上版本的普通字典默认保留插入顺序,你现有代码的问题在于dict.popitem()默认按**后进先出(LIFO)**规则删除最后添加的条目,要删除最早添加的条目只需修改popitem的参数即可。

方法1:直接修改现有代码(适配Python 3.7+)

将popitem()改为popitem(last=False),该参数指定按先进先出(FIFO)规则弹出最早插入的条目:

import time

dictionary_power_readings = {}
while True:
    # Power为实际读取到的功率数值
    dictionary_power_readings[time.time()] = Power
    if len(dictionary_power_readings) > 400:
        # 弹出最早插入的条目
        dictionary_power_readings.popitem(last=False)
        # 运行机器学习模型

方法2:使用OrderedDict(兼容Python 3.7以下版本)

如果需要适配更低版本的Python,可以使用collections.OrderedDict,它显式支持插入顺序维护,同样通过popitem(last=False)删除最早条目:

import time
from collections import OrderedDict

dictionary_power_readings = OrderedDict()
while True:
    dictionary_power_readings[time.time()] = Power
    if len(dictionary_power_readings) > 400:
        dictionary_power_readings.popitem(last=False)
        # 运行机器学习模型

注意事项

  • 以time.time()作为键需要注意极端场景下的重复问题,若单次循环间隔小于系统时间戳精度(通常是1ms),可能出现键覆盖的情况,可搭配序号拼接等方式避免该问题。
  • 你示例代码中定义了未使用的thisdict变量,注意根据实际需求调整变量命名避免逻辑错误。
  • 两种方案都能稳定维持字典大小为400,保证输入到机器学习模型的特征长度一致。

内容的提问来源于stack exchange,提问作者resolver101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 05:06:02