首页 > 解决方案 > 了解python字典内存分配

问题描述

对于以下示例,我试图了解在删除键并向它们添加新键时字典的内存分配量。(因为这是一个单独的长程序,我已将其分组为多个部分 - 如果您觉得不可读,欢迎编辑问题)

例子:

d = {
    "one": 1,
    "two": 2,
    "three": 3
}

import sys
def get_size(obj):
    return sys.getsizeof(obj)

#section 1
print("d - without modification: ")
print(d)
print(get_size(d))

#section 2
print("d - after deletion of two: ")
del d["two"]
print(d)
print(get_size(d))

#section 3
print("d - after adding two_copy key: ")
d["two_copy"] = 2
print(d)
print(get_size(d))

#section 4
print("d - after adding few values modification: ")
d["three_copy"] = 3
d["four"] = 4
print(d)
print(get_size(d))

#section 5
import copy
d1 = copy.deepcopy(d)
print("d1 - after deepcopy of d: ")
print(d1)
print(get_size(d1))

输出:

d - without modification: 
{'two': 2, 'three': 3, 'one': 1}
288

d - after deletion of two: 
{'three': 3, 'one': 1}
288

d - after adding two_copy key: 
{'two_copy': 2, 'three': 3, 'one': 1}
288

d - after adding few values modification: 
{'two_copy': 2, 'three_copy': 3, 'four': 4, 'three': 3, 'one': 1}
288

d1 - after deepcopy of d: 
{'two_copy': 2, 'three': 3, 'one': 1, 'four': 4, 'three_copy': 3}
288

在上面的示例中,section 1是我们以前看到的正常示例。对于section 2为什么这里的大小与从字典中删除键之前相同?. 当我们向 中添加新键时section 3,它保持相同的大小。但是为什么在同一个字典中再添加两个新键而不增加它的大小呢?section 4

当我在中添加新键时section 4,大小section 4 and section 5返回不同的值,如下所示,

print("d - after adding few values modification: ")
d["three_copy"] = 3
d["four"] = 4
d["five"] = 5    # this is the newly added key
print(d)
print(get_size(d))

第 4 节和第 5 节的输出:

d - after adding few values modification: 
{'two_copy': 2, 'three_copy': 3, 'one': 1, 'four': 4, 'five': 5, 'three': 3}
480
d1 - after deepcopy of d: 
{'two_copy': 2, 'three_copy': 3, 'one': 1, 'five': 5, 'four': 4, 'three': 3}
480

为什么在同一程序上添加一个新密钥后大小会发生变化?

我已经用粗体标记了我所有的问题。请任何人帮助我了解幕后发生的事情?谢谢。

您可以在此处运行相同的程序。

标签: pythonpython-3.xdictionarymemorymemory-management

解决方案


推荐阅读