Skip to content
Advertisement

How allocation of memory for `dict` in Python works?

I was playing around with Dictionaries and found this.

JavaScript

Output:

JavaScript

The size of Dictionary length 7 and 10 is the same that is 196 but for length 11, it’s 344. Why are they same? Why does the size rise up with length 11? How does dictionary size work in Python?

Advertisement

Answer

When you create an empty dictionary, it preallocates the memory in chunks for initial few references it can store. As the dictionary adds more key-value pairs, it needs more memory.

But it doesn’t grow with each addition; each time it needs more space, it adds some chunk of memory which can accommodate “X” amount of key-value pairs, and once “X” amount is filled, another chunk of memory is allocated to dictionary.

Here’s a sample code to display change is dictionary’s size as the count of keys increases:

JavaScript

Here’s the output in Python 3.6.2:

JavaScript

Also, dictionary just stores a reference of memory that holds the keys and values, and doesn’t stores key-value itself as part of dict object. So neither the type nor the size of the data affect the result of sys.getsizeof() for the dictionary.

For example, size of both the below dicts is 280 Bytes

JavaScript

However here’s the difference between size of 'a' V/s 'a' * 1000000:

JavaScript
Advertisement