3

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

stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • 4
    Why do you expect the size to be 2 bytes? If your data is a bytestring as in your second example, you can use `len(dict[key])` to get its length in bytes, but the length in bytes of a particular value in the dict is not the same as the size of the dict itself. – BrenBarn Nov 09 '12 at 21:15
  • 1
    Do you need to send this over a network or something? Size will depend on how you serialize it. – tzaman Nov 09 '12 at 21:16
  • How are you getting 46 bytes and 6 bytes? That's twice what I'm getting: `>>> print([len(x) for x in d.values()]) #[23, 23, 23, 23]` and `print([len(x) for x in d.keys()]) #[3, 3, 3, 3]` – mgilson Nov 09 '12 at 21:21
  • yes, i get this after hexlifying the values - that's how i'll need to transfer them, hexlified... – stdcerr Nov 09 '12 at 21:27

1 Answers1

2

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]))
stdcerr
  • 13,725
  • 25
  • 71
  • 128