Data Containers: Class vs. Dictionary

It seems to me that dictionaries are encouraged to define classes and use classes. When should I use a dictionary over a class and vice versa?

For example, if I want to have a dictionary of people, and each person has a name and other attributes, two simple ways:

  • Create a dictionary of people. Each key will be a person’s name, and the value will be a dictionary of all the attributes that a person has.

  • Create a Person class that contains these attributes, and then enter the Person s dictionary, the name will be the key and the Person object.

Both solutions seem valid and achieve the goal, but still it seems that python dictionaries are the way to go. The implementations are quite different so that if I wanted to switch back and forth, I could start a lot of changes to move from a class-based implementation to a dictionary-based implementation and vice versa.

So what am I trading?

+4
source share
2 answers

A dictionary is a great way to get started or experiment with approaches to solving a problem. They do not replace well-designed classes. Sometimes it’s the right “final decision" and the most efficient way of processing "I only need to transfer some data." I find it useful to start with the dictionary sometimes and, as a rule, ending with writing several functions to provide additional behavior that I need for the specific case I'm working on. At some point, I usually find that it would be more neat and cleaner to switch to using a class instead of a dictionary. This is usually determined by the number and complexity of the behavior that is needed to meet the needs of the situation. Since defining and using a class is so easy to do in Python, I find that I switch from dictionary plus functions to class quite early. (One thing that I discovered is that the “quick throw solution together” program takes care of life in so many cases - and it’s more productive to have real classes that can be expanded and reorganized, rather than a lot of code that ( ab) uses dictionaries.

+3
source

If you also do not want to encapsulate data behavior, you should use a dictionary. The class is used not only to store data, but also to indicate the operations performed with this data.

+2
source

Source: https://habr.com/ru/post/1434724/


All Articles