python - 了解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
为什么在同一程序上添加一个新密钥后大小会发生变化?
我已经用粗体标记了我所有的问题。请任何人帮助我了解幕后发生的事情?谢谢。
您可以在此处运行相同的程序。
解决方案
推荐阅读
- html - Internet Explorer 11,如何设置只读样式?
- php - 如何从 API 结果中选择特定值
- python - 简单来说super()的用例是什么
- ios - 对 AudioKit FM 振荡器参数执行基本算术运算:插值和时间转换
- ssl - Kubernetes 添加域名和 SSL
- javascript - Angular:覆盖嵌套组件的scss样式
- java - Java 时区数据库与 IANA 数据
- mathjax - 哪些选项可以让盲人和视障人士使用 MathJax?
- python - 无法在 selenium chromedriver 上添加超过 20 个扩展
- git - 如何将 gitlab 上的分支放入 github?