Internal Structure of Python Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized
The dictionary consists of a number of buckets. Each of these buckets contains the hash code of the object that contains the key-value pair. A pointer to the key object and a pointer to the value object.
The below diagram shows the internal structure of the dictionary:
The dictionary starts with 8 empty buckets. This is then resized by doubling the number of entries whenever its capacity is reached. This sums up to at least 12 bytes on a 32bit machine and 24 bytes on a 64bit machine
Example 1: An empty python dictionary consumes 240 bytes
Example 2. The first time we create a dictionary it contains only 8 slots that can be filled with key-value pairs.
As you can see the size of the dictionary is still the same after adding something to it. The dictionary stores in the bucket which is not full yet.
The key-values not stored in the dictionary itself the size of the dictionary doesn’t change even if we increase the size of its value
Size of dictionary -> 240 Size of a -> 50
Size of dicitonary -> 240 Size of a -> 50
Example 4: If we remove the items from a dictionary the size of the dictionary will still be the same.
Here, you can see the dictionary hasn’t released the memory it has allocated. It removes the reference from the hash table but the value is in the memory. Since it is not allocated may become part of garbage collection.
Example 5: If we empty the dictionary using the clear method the size of it is 72 bytes less than the initialized empty dictionary i.e. 240 bytes
This is because the method clears up memory. It also clears the initial default space i.e., 8 buckets allocated within the dictionary.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course