How to use built-in Dictionaries In Python

We all are very familiar with dictionary data type in Python. It’s a way of storing data in form of keys and values. But when it comes to memory management, dictionary isn’t the best. In fact, it’s the worst. Let’s see this with an example:




# importing the sys library
import sys 
  
Coordinates = {'x':3, 'y':0, 'z':1}
  
print(sys.getsizeof(Coordinates))


Output:

288

We see that one instance of the data type dictionary takes 288 bytes. Hence it will consume ample amount of memory when we will have many instances:

So, we conclude that dictionary is not suitable when dealing with memory-efficient programs.

Tips to reduce Python object size

We all know a very common drawback of Python when compared to programming languages such as C or C++. It is significantly slower and isn’t quite suitable to perform memory-intensive tasks as Python objects consume a lot of memory. This can result in memory problems when dealing with certain tasks. When the RAM becomes overloaded with tasks during execution and programs start freezing or behaving unnaturally, we call it a Memory problem.

Let’s look at some ways in which we can use this memory effectively and reduce the size of objects.

Similar Reads

Using built-in Dictionaries:

We all are very familiar with dictionary data type in Python. It’s a way of storing data in form of keys and values. But when it comes to memory management, dictionary isn’t the best. In fact, it’s the worst. Let’s see this with an example:...

Using tuples:

Tuples are perfect for storing immutable data values and is also quite efficient as compared to dictionary in reducing memory usage:...

Using class:

By arranging the code inside classes, we can significantly reduce memory consumption as compared to using dictionary and tuple....

Using recordclass:

Recordclass is a fairly new Python library. It comes with the support to record types which isn’t in-built in Python. Since recordclass is a third-party module licensed by MIT, we need to install it first by typing this into the terminal:...

Using dataobjects:

In previous example, while using recordclass, even the garbage values are collected thus wasting unnecessary memory. This means that there is still a scope of optimization. That’s exactly were dataobjects come in use. The dataobject functionality comes under the recordclass module with a specialty that it does not contribute towards any garbage values....