Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how many space assigned for empty dictionary in python? [duplicate]

If we create an empty dictionary, like: idict = {}, how many spaces are assigned for this dictionary ? I know for the list, if we initialize a list like ilist = [], it will always over-allocate the size, first is 4 space, then 8.
What about a dictionary ?

like image 645
umassjin Avatar asked Jul 30 '26 16:07

umassjin


1 Answers

Well, dictionaries don't store the actual string inside them, it works a bit like C/C++ pointers, so you only get a constant overhead in the dictionary for every element.

Testing against

import sys
x = {}
sys.getsizeof(x)

The dictionary itself consists of a number of buckets, each containing:

  • the hash code of the object currently stored (that is not predictable from the position of the bucket due to the collision resolution strategy used)

  • a pointer to the key object a pointer to the value

  • object in total at least 12 bytes on 32bit and 24 bytes on 64bit.

The dictionary starts out with 8 empty buckets and is resized by doubling the number of entries whenever its capacity is reached (currently (2n+1)/3).

like image 128
Navneet Avatar answered Aug 01 '26 04:08

Navneet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!