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

Python动态字典删除异常:删除指定key元素却影响全字典

问题:动态生成字典中修改单个时间段的vehicle_ids导致所有时间段同步变化

动态生成包含时间段的字典时,尝试移除特定时间段“01:01:00 to 01:30:00”下的vehicle id 11,执行remove操作后,所有时间段的vehicle_ids都丢失了11;但静态字典可正常运行,仅动态生成的字典存在该问题。

问题根源

核心原因是可变对象的引用传递:Python中列表是可变对象,代码里每次循环执行default_available_vehicle = {"vehicle_ids": vehicle_ids}时,并没有为每个时间段创建新的列表,而是将同一个vehicle_ids列表的内存引用赋值给了所有时间段的字典。因此所有时间段的vehicle_ids指向的是内存中的同一个列表,修改任意一个都会同步影响所有。

解决方案

只需要在循环中为每个时间段创建独立的列表副本即可,有两种常用方式:

方式1:使用列表的copy()方法创建副本

修改get_default_time_slot函数中创建字典的行:

default_available_vehicle = {"vehicle_ids": vehicle_ids.copy()}

方式2:使用list()构造函数创建副本

也可以写成:

default_available_vehicle = {"vehicle_ids": list(vehicle_ids)}

修改后的完整代码

import json
from datetime import timedelta

time_slots = {}

vehicle_ids = [11, 12]


def convert_time_two_digit(time_to_convert):
    index_of_semicolun = str(time_to_convert).find(":")
    if index_of_semicolun == 1:
        return "0" + time_to_convert
    else:
        return time_to_convert


def get_default_time_slot():
    for i in range(0, 5):
        if i == 0:
            start_time = timedelta(minutes=00)
            end_time = start_time + timedelta(minutes=30)
        else:
            start_time = end_time + timedelta(minutes=1)
            end_time = start_time + timedelta(minutes=29)
        # 创建独立的列表副本,避免引用同一内存对象
        default_available_vehicle = {"vehicle_ids": vehicle_ids.copy()}
        time_slots[convert_time_two_digit(str(start_time)) + " to " + convert_time_two_digit(str(end_time))] = \
            default_available_vehicle


get_default_time_slot()
timeslotsJson = json.dumps(time_slots, indent=4)
print("修改前的字典:")
print(timeslotsJson)

time_slots["01:01:00 to 01:30:00"]["vehicle_ids"].remove(11)
timeslotsJson = json.dumps(time_slots, indent=4)
print("\n修改后的字典:")
print(timeslotsJson)

修改后的输出(符合预期)

{
    "00:00:00 to 00:30:00": {
        "vehicle_ids": [
            11, 12
        ]
    },
    "00:31:00 to 01:00:00": {
        "vehicle_ids": [
            11, 12
        ]
    },
    "01:01:00 to 01:30:00": {
        "vehicle_ids": [
            12
        ]
    },
    "01:31:00 to 02:00:00": {
        "vehicle_ids": [
            11, 12
        ]
    },
    "02:01:00 to 02:30:00": {
        "vehicle_ids": [
            11, 12
        ]
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:24:18