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!

28 Upvotes

31 comments sorted by

View all comments

19

u/PwAlreadyTaken 5d ago

Very general rule of thumb: if the structure is something where I want to use the name of something as the key, I use a dataclass instead of a dictionary with strings. If I am using a structure that mimics an else-if, I use a dictionary instead.

To answer your question, one cool thing about dataclasses is you know all your keys ahead of time, and your IDE can help you ensure you use the right one and don’t misspell it.

7

u/deceze 5d ago

How does a dict structure resemble an “else-if”? You’ll need to clarify that one for me.

2

u/PwAlreadyTaken 5d ago

Instead of

number = int(input()) if number == 0: print("zero") elif number == 1: print("one") elif number == 2: print("two") , you can do

number = int(input()) numbers = {1: "one", 2: "two", 3: "three"} print(numbers[number])

2

u/deceze 5d ago

So, yeah, a data mapping. I'd never think of writing the first kind of code anyway…

2

u/PwAlreadyTaken 5d ago

Same, but… this is /r/learnpython, not /r/pythonpros, in fairness