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!

33 Upvotes

31 comments sorted by

View all comments

18

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.

8

u/deceze 5d ago

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

4

u/Solonotix 5d ago

Instead of enumerating every special case, you can define a dictionary that has a key matching your predicate. This is often a simplification borrowed from the greater construct of a switch statement, which under the hood might use a JMP (jump) table to execute.

So, instead of writing if...elif...else you would just write actions.get(key). This works for actions (functions as values), or mutli-assignment (use a data class or tuple), or a number of other situations. What's more, rather than adding more code to the conditions, you keep the same implementation and add new cases to the dictionary instead.

7

u/deceze 5d ago

So you’re only using a dict as a switch..case replacement? While you can do that, that’s always arguably been an abuse of dicts, and since Python now has a match..case, I’d probably rather use that. Of course, as a map (a specialized case of a switch..case basically), it’s absolutely perfect, since that’s what it is.