Saturday, November 16, 2024
Google search engine
HomeLanguagesGet size of a Dictionary in Python

Get size of a Dictionary in Python

These routines can be particularly useful when serving JSON objects over APIs since they can be used to keep the length and size of JSON objects under control. Web servers have restrictions on the size of JSON objects served via APIs.

Finding the Size of the Dictionary in Bytes

The size of a Dictionary means the amount of memory (in bytes) occupied by a Dictionary object. In this article, we will learn various ways to get the size of a Python Dictionary.

Get Size of Dictionary using getsizeof() function

The getsizeof() function belongs to python’s sys module which helps us to determine the memory size of the dictionary object in bytes.

Python3




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")


Output:

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

Get Size of Dictionary using __sizeof__() method

Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.

Python3




# 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")


Output:

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

RELATED ARTICLES

Most Popular

Recent Comments