Do Ordered Dictionaries in Python Consume More Memory than Regular Dictionaries?

Question
You are considered using ordered dictionaries in Python (e.g., because of the way they handle temporal data). Will your program use more memory this way compared to using a regular dictionary?

Answer
Yes. All things being equal, ordered dictionaries use more memory than normal dictionaries.

# You will see that Python 3's ordered dictionaries consume more memory than regular dictionaries
# This was adapted from https://lerner.co.il/2019/05/12/python-dicts-and-memory-usage/

import sys
from collections import OrderedDict

x = OrderedDict()
y = {}

for i in range(1, 123456):
    x[i] = "filler text"
    y[i] = "filler text"


print(sys.getsizeof(x))
print("The size of the ordered dictionary is above and the regular dictionary is below.")
print(sys.getsizeof(y))

Leave a comment

Your email address will not be published. Required fields are marked *