get size of populated dictionary

stdcerr picture stdcerr · Nov 9, 2012 · Viewed 11.5k times · Source

I would like to get the size of a populated dictionary in python. I tried this:

>>> dict = {'1':1}
>>> import sys
>>> print dict
{'1': 1}
>>> sys.getsizeof(dict)
140

but this apparently wouldn't do it. The return value I'd expect is 2 (Bytes). I'll have a dictionary with contents like:

{'L\xa3\x93': '\x15\x015\x02\x00\x00\x00\x01\x02\x02\x04\x1f\x01=\x00\x9d\x00^\x00e\x04\x00\x0b', '\\\xe7\xe6': '\x15\x01=\x02\x00\x00\x00\x01\x02\x02\x04\x1f\x01B\x00\xa1\x00_\x00c\x04\x02\x17', '\\\xe8"': '\x15\xff\x1d\x02\x00\x00\x00\x01\x02\x02\x04\x1f\x01:\x00\x98\x00Z\x00_\x04\x02\x0b', '\\\xe6@': '\x15\x014\x02\x00\x00\x00\x01\x02\x02\x04\x1f\x01@\x00\x9c\x00\\\x00b\x04\x00\x0b'}

and I want to know how many Bytes of data I need to send. my index is 6 Bytes but how long is the content? I know here it's 46Bytes per index, so I'd like to know that I need to transmit 4*(6+46) Bytes.... How do I do this best?

Thanks, Ron

Answer

stdcerr picture stdcerr · Nov 9, 2012

So, does only this give me the real length when I need to transmit the content Byte by Byte?

#non_mem_macs is my dictionary
for idx in non_mem_macs:
    non_mem_macs_len += len(hexlify(idx))
    non_mem_macs_len += len(hexlify(non_mem_macs[idx]))