Python Tricks #26 - Your Dict Size

in programming •  3 months ago 
# Empty dict size.
>>> d = {}
>>> import sys
>>> sys.getsizeof(d)
240

# It's the same size for first eight slots for key-value pairs.
# sys.getsizeof returns size of the data structure not the data inside of it.
>>> d['a'] = 1
>>> sys.getsizeof(d)
240

# The key-value pairs themselves aren’t stored in the dict itself.
# They are just a reference to the place in memory that holds the keys and values.
# Type nor size of the data affect the result of “sys.getsizeof” for a dictionary.
>>> d['a'] = 'a' * 100000
>>> sys.getsizeof(d)
240

# Each time a dict needs more space, it allocates more than it needs.
>>> d = {}
>>> for one_letter in 'abcdefghijklmnopqrstuvwxyz':
        d[one_letter] = one_letter
        print(f'{len(d)}, sys.getsizeof(d) = {sys.getsizeof(d)}')
1, sys.getsizeof(d) = 240
2, sys.getsizeof(d) = 240
3, sys.getsizeof(d) = 240
4, sys.getsizeof(d) = 240
5, sys.getsizeof(d) = 240
6, sys.getsizeof(d) = 368
7, sys.getsizeof(d) = 368
8, sys.getsizeof(d) = 368
9, sys.getsizeof(d) = 368
10, sys.getsizeof(d) = 368
11, sys.getsizeof(d) = 648
12, sys.getsizeof(d) = 648
13, sys.getsizeof(d) = 648
14, sys.getsizeof(d) = 648
15, sys.getsizeof(d) = 648
16, sys.getsizeof(d) = 648
17, sys.getsizeof(d) = 648
18, sys.getsizeof(d) = 648
19, sys.getsizeof(d) = 648
20, sys.getsizeof(d) = 648
21, sys.getsizeof(d) = 648
22, sys.getsizeof(d) = 1184
23, sys.getsizeof(d) = 1184
24, sys.getsizeof(d) = 1184
25, sys.getsizeof(d) = 1184
26, sys.getsizeof(d) = 1184

# Deleting items doesn't free the memory.
>>> for key in list(d.keys()):
        d.pop(key)
>>> len(d)
0
>>> sys.getsizeof(d)
1184

# To free memory use "dict.clear" method.
>>> d.clear()
>>> len(d)
0
>>> sys.getsizeof(d)
72

# After "dict.clear" the size will grow to initial 240 after adding first key-value pair.
>>> d['a'] = 1
>>> len(d)
0
>>> sys.getsizeof(d)
240
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!