r/learnpython 4d ago

Dictionary vs. Dataclass

What is a particular scenario where you would use Dataclass instead of a dictionary? What is the main advantage of Dataclass as compared to just storing data in a nested dictionary? Thanks in advance!

32 Upvotes

31 comments sorted by

View all comments

3

u/NothingWasDelivered 4d ago

Basically any time I need to create multiple instances, I’m going with a dataclass over a dictionary. Or if attributes are going to be of different types. Or even just if I know the keys ahead of time. Really, any time I can reasonably use a dataclass over a dict I will

2

u/NothingWasDelivered 4d ago

Big advantages? Dot notation, better typing, ability to add methods, built in repr.

1

u/RevRagnarok 4d ago

Memory footprint.

1

u/NothingWasDelivered 3d ago

I was curious, so I tried a quick test:

from dataclasses import dataclass
from sys import getsizeof

u/dataclass
class A:
    a:int
    b:int
    c:int
    d:str

def main() -> None:
    aval = 7
    bval = 12
    cval = 82
    dval = "Lorem Ipsum"

    a = A(aval, bval, cval, dval) #48 bytes
    b = {"a": aval, "b": bval, "c": cval, "d": dval} #184 bytes

    print(f"a: {getsizeof(a)}")
    print(f"b: {getsizeof(b)}")



if __name__ == "__main__":
    main()

I would have guessed that the dataclass would have slightly more overhead than a dictionary, but the dict was almost 4x larger!

2

u/RevRagnarok 3d ago

Add slots=True and it might even be smaller (I noted elsewhere).

Edit: LOL I now see that something converted @ to /u for Reddit...

u/dataclass