Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this dict of 7 items only consume 368 bytes?

Tags:

python

After some indepth reading, all documentation leads to state two things about dictionaries:

  • They instantiate with enough capacity for '8' items
  • They implicitly resize at 2/3 full (4x under 50,000 items and 2x above)

If that is the case, why does this dictionary only consume 368 bytes of RAM, when an empty dictionary takes 240 bytes, shouldn't this of resized 4x, e.g: 960 bytes?

    >>> getsizeof(dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7))
    368
    >>> getsizeof(dict(a=1,b=2,c=3))
    240

Am I being misinformed or misunderstanding something core here? Did something change with regards to this information on python 3.7?

like image 830
symon Avatar asked Apr 30 '19 18:04

symon


People also ask

How much memory does a Python dict use?

In other words, our dictionary, with nothing in it at all, consumes 240 bytes. Not bad; given how often dictionaries are used in Python, it's good to know that they don't normally consume that much memory.

How much memory does a dictionary use?

That means you need about 1 MB of memory to store the entire dictionary. Of course you can deflate it (zip) and store in memory, with a compression rate of about 90%. That means 100 KB.

Do dictionaries use less memory than lists?

Memory Consumption by dict vs list of tuples. Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory consumption of both the datatypes when both are empty.

Do Python dictionaries have a size limit?

There is in principle no size limitation to a dictionary in Python, except the capacity of your available memory (RAM + Swap space).


1 Answers

import sys
dictt=dict()
array=[]
for i in range(0,1000):
    dictt[i]=i
    array.append(sys.getsizeof(dictt))
print(array)

numberarray=[]
for i in range(1,1001):
    numberarray.append(i)

import matplotlib.pyplot as plt
plt.plot(numberarray,array)
plt.ylabel('memory')
plt.xlabel("items")
plt.show()

enter image description here

now visualize the question helps a lot. you got a nice debating topic. enter image description here

you should refer: http://www.jessicayung.com/how-python-implements-dictionaries/

like image 115
Jainil Patel Avatar answered Sep 19 '22 06:09

Jainil Patel