deepCopy会复制从旧字典中删除后留下的空间吗?

时间:2017-06-20 17:53:30

标签: python dictionary

我正在尝试根据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()

两种方式都不起作用。内存没有被释放。

源代码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

源代码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

讨论后的源代码

根据评论,我执行了以下操作并使用深度复制删除了参考。似乎它正在发挥作用。这是正确的吗?

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)

0 个答案:

没有答案