我正在尝试根据Python reclaiming memory after deleting items in a dictionary 从字典中删除密钥。后者提出的一个解决方案是:
通过复制旧词典来创建新词典
在源代码1 中,我执行了以下操作:
new_flights
del flights[key]
new_flights = copy.deepcopy(flights)
在源代码2 中,我执行了以下操作:
new_flights
new_flights[key] = flights[key]
flights.clear()
两种方式都不起作用。内存没有被释放。
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
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
根据评论,我执行了以下操作并使用深度复制删除了参考。似乎它正在发挥作用。这是正确的吗?
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)