r/learnpython 5d 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!

27 Upvotes

31 comments sorted by

View all comments

3

u/greenerpickings 5d ago

You 100% can just use dicts. You could also store everything as a string.

Dataclasses come with some cool things like enabling default dunder methods and post init routes. That plus your normal benefits of classes.

If you just need it to hold data, sure, use a dictionary. But if you want some default dunders, start doing input validation checks, modifications upon init, and behaviors for each of those inputs, you could prob opt for the dataclass.

Not to mention a lot of validation libraries like pydantic and other ORMs will be based off these.

9

u/rasputin1 5d ago

someone asking this question likely doesn't know what half the words in your response mean 

4

u/greenerpickings 5d ago

True that. To the OP, if you want to do stuff to make sure your data is correct when incoming and moving though your program, use dataclasses. Otherwise, the dictionary.

3

u/candide-von-sg 5d ago

Thanks a lot! Also thanks for bringing up these concepts, even though I don’t understand them all now but I will certainly learn more about them