I am trying to delete keys from a dictionary according to Python reclaiming memory after deleting items in a dictionary . One solution proposed in the latter is:
to create a new dictionary by copying the old dictionary
In source code 1 I did the following:
- I create a new dictionary
new_flights
- delete the key
del flights[key]
- finally use
new_flights = copy.deepcopy(flights)
In source code 2 I did the following:
- I create a new dictionary
new_flights
- copy to new dictionary
new_flights[key] = flights[key]
- finally
flights.clear()
Both ways didn't work. The memory is not being freed.
Source code 1
def remove_old_departure_dates(flights, search_date):
new_flights = defaultdict(lambda : defaultdict(list))
s_date = datetime.strptime(search_date,'%m/%d/%y')
for key in flights.keys():
dep_date = datetime.strptime(key.DDATE,'%m/%d/%y')
if(s_date > dep_date):
del flights[key]
new_flights = copy.deepcopy(flights)
flights.clear()
return new_flights
Source code 2
def remove_old_departure_dates(flights, search_date):
new_flights = defaultdict(lambda : defaultdict(list))
s_date = datetime.strptime(search_date,'%m/%d/%y')
for key in flights.keys():
dep_date = datetime.strptime(key.DDATE,'%m/%d/%y')
if(s_date > dep_date):
new_flights[key] = flights[key]
flights.clear()
return new_flights
Source code after discussion
Based on the comments I did the following and used a deepcopy to remove the reference. Seems that it's working. Is that something correct?
def remove_old_departure_dates(flights, search_date):
old_flights = defaultdict(lambda : defaultdict(list))
new_flights = defaultdict(lambda : defaultdict(list))
s_date = datetime.strptime(search_date,'%m/%d/%y')
for key in flights.keys():
dep_date = datetime.strptime(key.DDATE,'%m/%d/%y')
if(s_date > dep_date):
print "removing dates " + key.DDATE +" "+search_date
old_flights[key] = copy.deepcopy(flights[key])
else:
new_flights[key] = copy.deepcopy(flights[key])
return (old_flights, new_flights)