Skip to content
Advertisement

Element is removed from whole dictonary instead of particular key in dynamic dictonary in python

I am creating a dynamic dictionary. I want to remove the element from a particular array but it is removed from the whole dictionary. In below code I want to remove vehicle id 11 from the time slot “01:01:00 to 01:30:00”. This code removes vehicle id 11 from the whole dictionary.

JavaScript

Actual Output

JavaScript

Expected output should be

JavaScript

It is working fine when I define a static dictionary. But that is not the solution. Thanks

Advertisement

Answer

Your default_available_vehicle is a dictionary that contains a reference to the same list for all timestamps. This means that when you attempt to remove an element from the list e.g. using logic similar to the following:

JavaScript

It will appear as if 11 has been removed for all the timestamps since they are referring to the same global list.

One solution, assuming you wish to keep the global vehicle_ids list, is to create a new copy of the list in your loop. You can do this by using vehicle_ids.copy() instead i.e.

JavaScript

Alternatively, you may wish to restructure your code to remove the need for the global variable. You can simply initialise the list in your loop if the values for the list are known:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement