I have dictionary with following format:
Demo code:
>>> import pprint
>>> pprint.pprint(data)
{\'lookup\': {\'F01\': \'\\n.custom1
Dictionaries and lists store references (like every other standard container in Python). sys.getsizeof()
doesn't follow references, it gives you the memory footprint of the C structure only. The references are C pointers; their size depends on your specific platform.
Converting a dictionary to a string recursively converts the contents to (repr()
) strings too, so all those references are then dereferenced and included in the output. Note that this is not an accurate reflection of the memory size for the original object; strings contain characters, it depends on your exact Python version, OS and range of Unicode codepoints used how much memory each character takes, and the character count has a non-linear relationship to the actual object being reflected.
If you want to know the memory footprint of a dictionary with the contents you need to do so recursively. Take into account that a dictionary can contain references to itself (directly or indirectly), or that any object can have multiple references to it and should only be counted once. I'd use the id() function to track what objects have already been handled.
There are already several posts on Stack Overflow that discuss calculating memory size for containers using recursion or other tools, see Deep version of sys.getsizeof, Python deep getsizeof list with contents?, and Memory-usage of dictionary in Python? for some examples.