Memory size of a dictionary

EasyDictionary Programs · 17 of 94

Write a Python program to get the memory size of a dictionary with sys.getsizeof, and its number of items.

Advertisement
Input
{"name": "virat", "sport": "cricket"}
Output
2 items
True | bytes on this Python: 184

Approach

  1. sys.getsizeof gives the size of the dict object itself, len the item count.

Solution

Python
import sys d = {"name": "virat", "sport": "cricket"}print(len(d), "items")print(sys.getsizeof(d) > 0, "| bytes on this Python:", sys.getsizeof(d))
Output
2 items
True | bytes on this Python: 184
Note

The byte count depends on the Python version and platform, and it does not include the keys and values themselves.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs