📜  在Python中查找字典的大小

📅  最后修改于: 2022-05-13 01:55:34.761000             🧑  作者: Mango

在Python中查找字典的大小

Python中的字典是数据值的无序集合,用于像地图一样存储数据值,与其他仅将单个值作为元素保存的数据类型不同,字典包含键:值对。字典中提供了键值,使其更加优化。 Dictionary 的大小是指 Dictionary 对象占用的内存量(以字节为单位)。在本文中,我们将学习各种获取Python字典大小的方法。

1.使用getsizeof()函数:

getsizeof()函数属于 python 的 sys 模块。它已在以下示例中实现。

示例 1:

import sys
  
# sample Dictionaries
dic1 = {"A": 1, "B": 2, "C": 3} 
dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"}
dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"}
  
# print the sizes of sample Dictionaries
print("Size of dic1: " + str(sys.getsizeof(dic1)) + "bytes")
print("Size of dic2: " + str(sys.getsizeof(dic2)) + "bytes")
print("Size of dic3: " + str(sys.getsizeof(dic3)) + "bytes")

输出:

Size of dic1: 216bytes
Size of dic2: 216bytes
Size of dic3: 216bytes

1.使用内置__sizeof__()方法:

Python还有一个内置的 __sizeof__() 方法来确定对象的空间分配,而无需任何额外的垃圾值。它已在以下示例中实现。
示例 2:

# sample Dictionaries
dic1 = {"A": 1, "B": 2, "C": 3} 
dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"}
dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"}
  
# print the sizes of sample Dictionaries
print("Size of dic1: " + str(dic1.__sizeof__()) + "bytes")
print("Size of dic2: " + str(dic2.__sizeof__()) + "bytes")
print("Size of dic3: " + str(dic3.__sizeof__()) + "bytes")

输出:

Size of dic1: 216bytes
Size of dic2: 216bytes
Size of dic3: 216bytes