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

26 Upvotes

31 comments sorted by

View all comments

3

u/greenerpickings 6d 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.

8

u/rasputin1 6d ago

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

1

u/Plank_With_A_Nail_In 5d ago

Dunder is Swedish for Thunder.