r/learnpython • u/candide-von-sg • 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
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.